处理null的优雅方法 - 在2个变量中只需要单个null值

use*_*342 2 java logic

有没有更好的方法来解决这个问题?我有两个变量X和Y.X和Y都不能为空.他们两个都无法设置.其中只有一个应为null

例如:

if (x && y)
    return err;
if (x == null && y == null)
    return err;
if (x)
 …do something with x
if (y)
..do something with y
Run Code Online (Sandbox Code Playgroud)

shm*_*sel 6

您可以合并错误检查,如下所示:

if ((x == null) == (y == null)) {
    return err;
}
if (x != null) {
    // do something with x
} else {
    // do something with y
}
Run Code Online (Sandbox Code Playgroud)

  • 换句话说,即`((x == null)!=(y == null))`,你也可以使用[boolean logical exclusive-or operator](https://docs.oracle.com/javase /specs/jls/se8/html/jls-15.html#jls-15.22.2),即`((x == null)^(y == null))`,由于运算符优先规则,不需要额外的括号,即`(x == null ^ y == null)`. (2认同)