Skip to content

Instantly share code, notes, and snippets.

@guyhughes
Last active March 21, 2016 19:07
Show Gist options
  • Select an option

  • Save guyhughes/5622dd6b403edc7146bc to your computer and use it in GitHub Desktop.

Select an option

Save guyhughes/5622dd6b403edc7146bc to your computer and use it in GitHub Desktop.
public class Foo implements Cloneable {
static class Bar {
public int i;
public Bar() { }
}
static class Qux {
public int a[];
public int b;
public Qux() { }
}
public int x;
public Foo.Bar y;
public Foo.Qux z;
/**
* do not worry about this.
*/
public Foo clone(){
try {
return (Foo)(super.clone());
} catch (CloneNotSupportedException e){
System.err.println("go home");
}
throw new RuntimeException("go home sally!");
}
/**
* Question 3.
*/
public static Foo deepcopy(final Foo original){
Foo shallowcopy = original.clone(); // don't worry about this line
// -- start here
Foo deepcopy = new Foo();
deepcopy.x = shallowcopy.x;
deepcopy.y = new Bar();
deepcopy.y.i = shallowcopy.y.i;
deepcopy.z = new Qux();
deepcopy.z.a = new int[shallowcopy.z.a.length];
System.arraycopy(shallowcopy.z.a,0,deepcopy.z.a,0,shallowcopy.z.a.length);
deepcopy.z.b = shallowcopy.z.b;
// -- end here
return deepcopy;
}
public String toString()
{
StringBuffer s = new StringBuffer();
s.append("[Foo]\n");
s.append("\tx = " + this.x + "\n");
s.append("\ty = ");
if (y == null) {
s.append("null");
}
else {
s.append("{\n");
s.append("\t\ti = " + y.i + ", \n");
s.append("\t}");
}
s.append("\n");
s.append("\tz = ");
if (z == null) {
s.append("null");
}
else {
s.append("{\n");
s.append("\t\ta = ");
if (z.a == null) {
s.append("null");
}
else{
s.append(java.util.Arrays.toString(z.a));
/*
* for(int i=0; i < z.a.length; i++){
* s.append(z.a[i]+" ");
* }
*/
} s.append(", \n");
s.append("\t\tb = " + z.b + "\n");
s.append("\t}");
}
s.append("\n");
return s.toString();
}
public static void main(String[] args)
{
testDeepCopy();
}
public static void testDeepCopy(){
Foo f = new Foo();
f.x = -1;
f.y = new Foo.Bar();
f.y.i = -23523;
f.z = new Foo.Qux();
f.z.a = new int[] {1324,12412,2435235,234,123};
f.z.b = 300;
System.out.println("Here is f");
System.out.println(f);
Foo f_deepcopy = Foo.deepcopy(f);
System.out.println("\n\nhere is f_deepcopy");
System.out.println(f_deepcopy);
System.out.println("\n\nmaking changes to f...");
f.x = 100;
f.y.i = 101;
f.z.a = new int[]{102,100,100,100};
f.z.b = 103;
System.out.println("\n\nHere is f");
System.out.println(f);
System.out.println("\n\nhere is f_deepcopy");
System.out.println(f_deepcopy);
}
public static void testToString(){
Foo f = new Foo();
System.out.println(f);
f.x = 1;
f.y = new Foo.Bar();
f.z = new Foo.Qux();
System.out.println(f);
f.z.a = new int[] { 1, 2, 3, 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 };
System.out.println(f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment