Reputation: 32071
I want to make a deep copy method. I seeked help here the other day with this issue, but that was for a copy constructor. Now I need a regular method. I have the code created (nonworking), but I'm just not understanding it completely.
public GhostList deepCopy(){
int length=this.getLength();
GhostList jadeed=new GhostList();
Ghost[] data = new Ghost[length];
for (int i=0;i<this.getLength();i++){
data[i] = new Ghost();
data[i].setX(this.ghosts[i].getX());
data[i].setY(this.ghosts[i].getY());
data[i].setColor(this.ghosts[i].getColor());
data[i].setDirection(this.ghosts[i].getDirection());
}
return jadeed;
}
Now when I create a new GhostList named jadeed, and then under that I create a new data array of ghosts, does it know that data belongs to the jadeed GhostList? I dont see how the two can be associated, even though they should be.
Also, I'm not getting the lengths to match up for the copy and this.object. What is my problem?
Upvotes: 1
Views: 1357
Reputation: 16736
If GhostList
and everything it's composed of is Serializable
, you can serialize the GhostList
instance into a byte array and re-read it. It's a few lines of code, unless you use `Jakarta Commons Lang - one line of code:
Upvotes: 0
Reputation: 455112
Your GhostList
class will have as its data member a reference to the array of Ghost
. You've not shown us the class definition, so lets say that member is named foo
. Now all you need to do is make the foo
reference of the newly created jadeed
object refer to the array of Ghost
which you've created and populated. You can do it as:
jadeed.foo = data;
before you return jadeed
.
Upvotes: 1
Reputation: 70701
First, you mentioned a copy constructor. If you already have that working, then all you need to do in your deepCopy
method is:
return new GhostList(this);
Let's forget that for now and get back to the code you posted. You are creating an array named data
but you never used it anywhere. Aren't you supposed to assign this array to jadeed
? Something like:
jadeed.ghosts = data;
And finally, instead of calling the method deepCopy
, it would be better to call it clone
and implement the Cloneable
interface. Doing this allows everyone to know how to get a copy of your object using a standard interface.
Upvotes: 2
Reputation: 18286
You created a new GhostList
and a new Ghost
array.
You fill in the Ghost
array and return the GhostList
but the returned GhostList
has nothing to do with the Ghost
array.
You should add all the new ghosts to the GhostList
Upvotes: 3