【发布时间】:2026-01-04 03:10:02
【问题描述】:
请各位大神指教一下:
片段 1:
public class ArrayKoPo {
public static int[] getArray() {
return null;
}
public static void main(String args[]) {
int i = 0;
try {
int j = getArray()[i++];
} catch (Exception e) {
System.out.println(i); //prints 1 <---- This one I expected.
}
}
}
片段 2:
public class ArrayKoPo {
public static int[][] getArray() {
return null;
}
public static void main(String args[]) {
int i = 0;
try {
int j = getArray()[i++][i++];
} catch (Exception e) {
System.out.println(i); //still prints 1 <---- This one I don't understand. I thought 2 will be printed.
}
}
}
为什么变量 i 在第二个代码块中没有增加两次?
我错过了什么?
谢谢。
【问题讨论】:
-
getArray()[i++]触发了NullPointerException,因此它无法在getArray()[i++]上索引[i++]。 Java 从左到右计算 :-) -
我明白了。这就是我在那里错过的。我认为括号内的所有表达式将在整个索引操作发生之前首先(从左到右)进行评估,但正如您所指出的,索引操作从左到右“按索引”发生。谢谢你解释! :)
-
我已经用充足的证据修改了我的答案!
标签: java arrays post-increment