/*
* Some processing going on in original array
*
*
* For debugging purposes I check backup and it has change
*/
this.original = backup; //no that important; backup changed before this
Can anybody hint out what's happening. I didn't touch backup in the whole processing. Isn't clone supposed to create new clone instead of just copying over the reference variable? Or do I perhaps need to override clone() with a custom method because perhaps it doesn't work properly with custom types (such as type1 above)? Or am I just talking bunkers? I
public class Test {
public static void main(String[] args) {
Wheel w1 = new Wheel(5);
Wheel w2 = new Wheel(10);
Motorcycle m1 = new Motorcycle(w1, w2);
Motorcycle m2 = m1.correctClone();
m2.frontWheel.radius = 3;
System.out.println(m1.frontWheel.radius); //Prints 5, m1.frontWheel is not the same as m2.frontWheel
Motorcycle m3 = m1.incorrectClone();
m3.frontWheel.radius = 3;
System.out.println(m1.frontWheel.radius); //Prints 3, m1.frontWheel is the same as m2.frontWheel
}
}
class Motorcycle {
public Wheel frontWheel, backWheel;
public Motorcycle(Wheel front, Wheel back) {
this.frontWheel = front;
this.backWheel = back;
}
public Motorcycle correctClone() {
return new Motorcycle(frontWheel.clone(), backWheel.clone());
}
public Motorcycle incorrectClone() {
return new Motorcycle(frontWheel, backWheel);
}
}
class Wheel {
public int radius;
public Wheel(int radius) {
this.radius = radius;
}
public Wheel clone() {
return new Wheel(this.radius);
}
}
Name:
Anonymous2010-11-26 11:40
>>1
You have an array of references to arrays of references to objects.
When you clone your array of references you get a new array of references. Which still refer to the same old arrays of references to the same old objects.
In other words, clone() usually performs a shallow copy.