package cn.com.csuinfo;public class CloneTest {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("abc");
String str3 = new String();
int[] arr1 = {20,4,11,7,15,6,9,30,1,25};
int[] arr2 = new int[10];
arr2 = arr1.clone(); //ok. why?在Array类也没有重写clone()方法啊?
str3 = str1.clone(); //error code,
}
}str3 = str1.clone(); //error code,这行代码编译报错的原因是什么,请高手指点下!!谢谢
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("abc");
String str3 = new String();
int[] arr1 = {20,4,11,7,15,6,9,30,1,25};
int[] arr2 = new int[10];
arr2 = arr1.clone(); //ok. why?在Array类也没有重写clone()方法啊?
str3 = str1.clone(); //error code,
}
}str3 = str1.clone(); //error code,这行代码编译报错的原因是什么,请高手指点下!!谢谢
Object 类的 clone 方法执行特定的克隆操作。
首先,如果此对象的类不能实现接口 Cloneable,则会抛出 CloneNotSupportedException。
所有的数组都被视为实现接口 CloneableObject 类本身不实现接口 Cloneable,
所以在类为 Object 的对象上调用 clone 方法将会导致在运行时抛出异常。
a. 什么时候使用shallow Clone,什么时候使用deep Clone,这个主要看具体对象的域是什么性质的,基本型别还是reference variable
b. 调用Clone()方法的对象所属的类(Class)必须implements Clonable接口,否则在调用Clone方法的时候会抛出CloneNotSupportedException。