What you have implemented is a shallow copy. To implement a deep copy, you must
change
data[i] = other.data[i];
to some thing that assigns a copy of other.data[i]
to data[i]
. How you do this depends on the Position
class. Possible alternatives are:
a copy constructor:
data[i] = new Position(other.data[i]);
a factory method:
data[i] = createPosition(other.data[i]);
clone:
data[i] = (Position) other.data[i].clone();
Notes:
- The above assume that the copy constructor, factory method and clone method respectively implement the "right" kind of copying, depending on the Position class; see below.
- The
clone
approach will only work if Position
explicitly supports it, and this is generally regarded as an inferior solution. Besides, you need to be aware that the native implementation clone
does a shallow copy.
In fact the general problem of implementing deep copying in Java is complicated. In the case of the Position
class, one would assume that the attributes are all primitive types (e.g. ints or doubles), and therefore a deep versus shallow copying is moot. But if there are reference attributes, then you have to rely on the copy constructor / factory method / clone method to do the kind of copying that you require. In each case it needs to be programmed in. And in the general case (where you have to deal with cycles) it is difficult and requires each class to implement special methods.
All in all, deep copying is best avoided in Java.
Finally, to answer your question about the Position
classes copy constructor works, I expect it is something like this:
public class Position {
private int x;
private int y;
...
public Position(Position other) {
this.x = other.x;
this.y = other.y;
}
...
}
As @Turtle says, there's no magic involved. You implement a copy constructor by hand.