Question

I have two classes, one class is called Client and the other one is call Department. The class Department stores an array of Clients.

I was making some tests to prove Deep Copy in Java, but it does not seem to work.

In the Department class I have a get method that returns the list of Clients that stores. For example:

public Client[] getClientList() {
        return clientList;
    } 

a method that returns the number of clients that I store:

public int getNumberClients() {
        return n;
    }

and one method that returns an specific Client from the clientList:

public Client getClient(int pos){
        return clientList[pos];
    }

In my main program I have created a certain number of Clients and store them into the Department class, specifically in the clientList attribute; something like this:

Client objCli1=new Cliente(...
...
Department objDep=new Department(100)
objDep.addClient(objCli1)
...

so now I want to return the array of Clients from the Department class into my main program, and copy their elements into another client Array. Something like this:

Client[] clientList;
int n=objDep.getNumberClients();
clientList=new Client[n];
for (int i=0;i<n;i++){
    clientList[i]=objDep.getClient(i);
}

So when I print the elements of clientList they are the same as the ones that I have in my Department class. The problem is that if I do something like this:

clientList[2].setName("Michaels")

it changes the name of the second client that I got stored in my Department class; I wonder why is that? because I have made a deep copy of the elements that I have in my Department class to the new clientList in my main program. So why is not working? Any hint how to do that it would be great.

Thanks

Was it helpful?

Solution

make a clone method in your client class. Like this

public Client clone(){
      Client client = new Client();
      client.name=name; 
      client.id=id;
      ...

      // copy each element property;

      return client;

 }

and use it here

Client[] clientList;
int n=objDep.getNumberClients();
clientList=new Client[n];
for (int i=0;i<n;i++){
   clientList[i]=objDep.getClient(i).clone();
}

OTHER TIPS

Youre not doing a deep copy of the object you are just referencing it thats why when you change the name from the first client it also changes from the one you said you copied it..

Solution:

Do a copy constructor in your Client class

public Client(Client client)
{
   this.name = client.getName();
}

In your copy loop

for (int i=0;i<n;i++){
    clientList[i]= new Client(objDep.getClient(i));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top