Skip to content

Instantly share code, notes, and snippets.

@vyazelenko
Created December 10, 2015 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vyazelenko/75cac9f97249cb760630 to your computer and use it in GitHub Desktop.
Save vyazelenko/75cac9f97249cb760630 to your computer and use it in GitHub Desktop.
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