我试图使用for循环初始化整数java数组中的对象,但在for循环退出后数组元素为null.
public static void main(String[] args) {
Integer[] x = new Integer[1];
for (Integer xx : x) {
xx = new Integer(1);
System.out.println("inside for loop "+xx.toString());
}
System.out.println("why isn't this 1? " + x[0]);
x[0] = new Integer(2);
for (Integer xx : x) {
System.out.println("Not it's okay: " + xx.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
但是在for循环退出后,数组元素为null.这是输出:
inside for loop 1
why isn't this 1? null
Not it's okay: 2
Run Code Online (Sandbox Code Playgroud)
为什么这个for循环的行为不一样for (i=0;i<1;i++){x[i]=1;} ?