java二維數組的使用需要注意的地方

來源:互聯網
上載者:User

如下所示的代碼,如果按照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()等方法。

今天上了這麼一個當,看來基礎還有待提高啊。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.