while 循环条件评估

while loop condition evaluation

我有一段代码涉及进入 while 循环的两个条件,但我对以下代码的输出和预期结果感到困惑:

while (curr != null && key.compareTo(curr.getKey()) > 0) {
  prev = curr;
  curr = prev.getNext();
  if (curr == null) {
    System.out.println(curr + " is null");
  }
}

当我 运行 这段代码时,我预计它会抛出一个空指针异常,因为 curr 为 null 并且我在 null 上调用一个方法,在消息被打印出来之后,但是它退出了正常循环,我想知道这是否是正常行为?从这里看来它确实一次评估一个条件,但我认为 while 循环在一个布尔表达式中评估括号内的所有内容?

我 运行 一个测试,我将 ope运行ds 换成 && 反过来发现它确实抛出了一个空指针异常!这是什么原因?

问。 while 循环条件是作为一个整体进行评估还是在决定是否进入循环之前一次评估一个条件?

&& 是短路(或简写)运算符。它将评估第一个条件,如果条件为真,则仅评估第二个条件。

因此,如果我的条件是 conditon1 && condition2,当且仅当条件 1 为真时,它才会计算条件 2。

因此,在您的情况下,它将评估非空条件 (curr != null),如果失败,则不会评估另一个条件,因此不会出现 NullPointerException,因此您会看到 while 循环正常退出。

 (curr != null && key.compareTo(curr.getKey()) 

&& 确保左边在 运行 右边

之前为真

&&和||运算符 "short-circuit",这意味着如果没有必要,它们不会计算右侧。

& 和 |运算符,当用作逻辑运算符时,总是计算双方。

这里有一个很好的解释 Java logical operator short-circuiting

There is only one case of short-circuiting for each operator, and they are:

false && ... - it is not necessary to know what the right hand side is, the result must be false
true || ... - it is not necessary to know what the right hand side is, the result must be true