Created
December 10, 2015 16:51
-
-
Save vyazelenko/75cac9f97249cb760630 to your computer and use it in GitHub Desktop.
Java code to demonstrate that clone() is shallow by default
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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