In java books and online tutorials it is stated that Object.clone()
method provides shallow copying unless Cloneable interface is used but in the code I implemented clone()
method without using Cloneable
interface and it is providing a deep copy instead of a shallow copy.
import java.util.GregorianCalendar;
public class test1 {
public static void main(String[] args) {
// create a gregorian calendar, which is an object
GregorianCalendar cal = new GregorianCalendar();
// clone object cal into object y
GregorianCalendar y = (GregorianCalendar) cal.clone();
// check if reference of y is equal to cal or not
System.out.println(cal==y);//it's output should be true if this is a shallow copy but it is false.
}
}
答案 0 :(得分:0)
GregorianCalendar
确实实现了Cloneable
接口,因此应该进行深层复制。
编辑:Java仅处理对对象的引用。因此,在这种情况下,由于GregorianCalendar
的{{1}}方法执行了深复制,因此复制引用的一种方法是将clone
分配给cal
,即{ {1}}。