当我学习java时,有人告诉我,一旦创建,数组的大小是固定的,无法更改。最近我一直在使用数组,并注意到类似于以下的代码不会产生错误:
public class Test {
private static String[][] smallArray = new String[4][4];
private static String[][] biggerArray = new String[21][21];
private static String[][] assignedLater;
public static void main(String args[]){
for(int i = 0; i < smallArray.length; i++){
for(int j = 0; j < smallArray[0].length; j++){
smallArray[i][j] = i + j + "";
}
}
for(int i = 0; i < biggerArray.length; i++){
for(int j = 0; j < biggerArray[0].length; j++){
biggerArray[i][j] = i + j + "";
}
}
assignedLater = smallArray;
//last element of last row
System.out.println(assignedLater[3][3]) //returns 6
assignedLater = biggerArray;
//new last element of new last row
System.out.println(assignedLater[20][20]) //returns 40
}
}
在玩了一会儿之后,我最终测试了以下内容:
public class Test {
private static String[][] smallArray = new String[2][4];
private static String[][] biggerArray = new String[2][21];
private static String[][] errorArray = new String[3][21];
private static String[][] assignedLater = new String[2][0];
public static void main(String args[]){
//fill arrays as in previous example
assignedLater = smallArray;
//last element of last row
System.out.println(assignedLater[1][3]) //returns 6
assignedLater = biggerArray;
//new last element of new last row
System.out.println(assignedLater[1][20]) //returns 21
assignedLater = errorArray; //no error
System.out.println(assignedLater[2][20]); // returns 22
}
}
这里发生了什么?
编辑 感谢您的回复,我特此明白为什么不可能的事情实际上并没有发生。