Re: [問題] 物件複製問題

看板java作者 (蟲蟲)時間13年前 (2011/06/13 23:03), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串4/4 (看更多)
借標題一用 爬了不少文章,clone()在某些情況下是管用的 但如果我的class裡面存在 二為陣列 clone 就派不上用場了 public class test_class implements Cloneable{ int a = 10; int[] b = {1,2,3}; String[][] c = {{"A","B","C"},{"A","B","C"}}; public test_class clone(){ try{ test_class copy = (test_class)super.clone(); copy.b = (int[])b.clone(); copy.c = (String[][])c.clone(); return copy; } catch (CloneNotSupportedException e){ e.printStackTrace(); return null; } } public static void main(String args[]){ test_class temp10 = new test_class(); test_class temp11 = temp10.clone(); temp10.a = 100; teno10.b[1] = 100; temp10.c[1][1] = "500"; System.out.println(temp10.a + " " + temp10.b[1] + " " + temp10.c[1][1]); System.out.println(temp11.a + " " + temp11.b[1] + " " + temp11.c[1][1]); } 顯示結果 100 100 500 10 2 500 表示class裡面變數為int,一維陣列都可順利複製,但二維陣列失敗 有解決辦法嗎? 明天就要交了...麻煩各位了,小弟在此感激不盡 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.168.161.57

06/13 23:20, , 1F
二維陣列複製了一個裝滿陣列位置的陣列
06/13 23:20, 1F

06/13 23:29, , 2F
可以解釋一下嗎? 不大懂...
06/13 23:29, 2F

06/13 23:50, , 3F
找到解決辦法了,在copy.c = c.clone();
06/13 23:50, 3F
文章代碼(AID): #1DzYR5QZ (java)
文章代碼(AID): #1DzYR5QZ (java)