gpt4 book ai didi

java - 数组引用表达式未完全计算

转载 作者:行者123 更新时间:2023-11-29 05:56:07 24 4
gpt4 key购买 nike

请各位大神指点一下:

片段 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 没有递增两次?

我错过了什么?

谢谢。

最佳答案

我相信它会像下面这样发生:

  1. 程序运行到 getArray() 的位置:返回 null。
  2. 然后程序移动到方括号,计算参数,并尝试进入数组。 (我不熟悉的Java魔术就发生在这里)
  3. 尝试失败并在查看第二个索引运算符之前生成异常。

如果我们要以另一种方式放置您的第二个代码段,它应该等同于以下内容(因此生成与第一个代码段相同的结果):

public class ArrayKoPo {

public static int[][] getArray() {
return null;
}

public static void main(String args[]) {
int i = 0;
try {
int[] j = getArray()[i++];
int k = j[i++];
} catch (Exception e) {
System.out.println(i);
}
}
}

关于java - 数组引用表达式未完全计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12066481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com