作者scribble08 (虫虫)
看板java
标题Re: [问题] 物件复制问题
时间Mon Jun 13 23:03:30 2011
借标题一用
爬了不少文章,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
1F:推 zhengdavy:二维阵列复制了一个装满阵列位置的阵列 06/13 23:20
2F:→ scribble08:可以解释一下吗? 不大懂... 06/13 23:29
3F:→ scribble08:找到解决办法了,在copy.c = c.clone(); 06/13 23:50