JAVA: Clones

Java cloning will return a shallow copy of the current object.

Vector<Object> objs1 = new Vector<Object>();
objs1.add(new Object());

Vector<Object> objs2 = (Vector<Object>) objs1.clone();

System.out.println(objs1 == objs2); // return false
System.out.println(objs1.elementAt(0) == objs2.elementAt(0)); // return true

This means that clone() creates a totally separate instance of the original, uses up the same amount of space, but each of its Object children point to the same data as the original copy.

No comments: