/*
* 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
Name:
Anonymous2010-11-26 10:59
Sometimes this anal acrobatics is more difficult than Category Theory.
Name:
Anonymous2010-11-26 11:03
Another disadvantage is that one often cannot access the clone() method on an abstract type. Most interfaces and abstract classes in Java do not specify a public clone() method. As a result, often the only way to use the clone() method is if you know the actual class of an object; which is contrary to the abstraction principle of using the most generic type possible. For example, if one has a List reference in Java, one cannot invoke clone() on that reference because List specifies no public clone() method. Actual implementations of List like ArrayList and LinkedList all generally have clone() methods themselves, but it is inconvenient and bad abstraction to carry around the actual class type of an object.
This seems relevant since type1 is an abstract how ever it doesn't throw any exceptions while executing?!
Name:
Anonymous2010-11-26 11:08
The program works if I use a for loop method instead to copy to another array but it would be nice to have a solution to this clone thing in 2 lines or less.
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.