Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java code to demonstrate that clone() is shallow by default
import java.util.Arrays;
import java.util.List;
class ClassWithState implements Cloneable {
int x = 15;
Long y = Long.MAX_VALUE / 3;
String z = new String("new Z");
List<String> data = Arrays.asList("a", "b", "and", "c");
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class CloneIsShallow {
public static void main(String[] args) throws Exception {
ClassWithState orig = new ClassWithState();
ClassWithState copy = (ClassWithState) orig.clone();
if (orig.x != copy.x || orig.y != copy.y || orig.z != copy.z || orig.data != copy.data) {
throw new AssertionError("ERROR");
}
System.out.println("OK");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment