如下所示的代碼,如果按照C語言來說則第二次輸出時只應該是數組的第一行全為零,可是事實上我們卻會看到第一行和第二行都為0:
代碼:
public class Test3 { public static void main(String[] args){ int test[][]={{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}, {13,14,15}}; for(int row=0;row<5;row++){ for(int col=0;col<3;col++){ System.out.print(test[row][col]+"\t"); } System.out.println(); } System.out.println("-------------------"); test[4]=test[3]; test[3]=test[2]; test[2]=test[1]; test[1]=test[0]; for(int col=0;col<3;col++){ test[0][col]=0; } for(int row=0;row<5;row++){ for(int col=0;col<3;col++){ System.out.print(test[row][col]+"\t"); } System.out.println(); } }}
運行結果:
分析產生這個問題的原因:
java中其實是沒有二維數組的,只不過java的一維數組可以是一個對象,則可知將幾個一維數組當做元素儲存到另一個一維數組中則可以得到二維數組。就這樣test[1]=test[0]後test[1]這個引用指向的是test[0]原來對應的對象,而test[0]也仍然指向這個對象,則使用for迴圈改變test[0]原來指向的對象的值後使用test[1]和test[0]這兩個引用取出的資料必然是一樣的。
當然如果還是想達到只複製前一行的值到這一行,則可以使用.clone()方法來實現,如下所示:
public class Test3 { public static void main(String[] args){ int test[][]={{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}, {13,14,15}}; for(int row=0;row<5;row++){ for(int col=0;col<3;col++){ System.out.print(test[row][col]+"\t"); } System.out.println(); } System.out.println("-------------------"); test[4]=test[3].clone(); //注意此處和上面的不同,都是將前一行數組對象的複製賦值給當前行 test[3]=test[2].clone(); test[2]=test[1].clone(); test[1]=test[0].clone(); for(int col=0;col<3;col++){ test[0][col]=0; } for(int row=0;row<5;row++){ for(int col=0;col<3;col++){ System.out.print(test[row][col]+"\t"); } System.out.println(); } }}
運行結果:
可以看出,第二次輸出中第一行和第二行的資料不一樣了。
總之,java是物件導向的語言,前往不要再拿C語言那一套來行事了,兩個對象如果只是要賦相同的值而不是指向相同的對象,一定要注意使用.clone()等方法。
今天上了這麼一個當,看來基礎還有待提高啊。