-1

I have Customer class which holds 5 fields. And I have 10 unique instance of Customer class in ArrayList<Customer> firstlist. I copied firstlist content to new ArrayList<Customer> secondlist list with method:

public void copy( ArrayList<Customer> a,  ArrayList<Customer> b){
 for (int i=0;i<a.size();i++){ b.add(a.get(0)); } }

Problem is if I change secondlist instances, it also changes firslist instances because of reference..

How can I copy firstlist instances to secondlist so that when I change secondlist instance it doesn't effect to firtlist instance(copy of itself). Is there any method which can do that?

user3521129
  • 91
  • 1
  • 1
  • 5

3 Answers3

0

Seems you need to clone the Customer instances.

Check the Cloneable interface:

http://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html

and implement it in Customer, then in your loop add clones to
the second list, not the originals: b.add(a.get(i).clone());.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

I suggest you add a clone to your Customer class by implementing Cloneable.

public void copy( ArrayList<Customer> a,  ArrayList<Customer> b){
  for (int i=0;i<a.size();i++){ 
    b.add(a.get(i).clone()); // get(i) I think. 
  } 
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You'll need some method of performing a deep copy of a Customer instance. There are several ways of doing this: implementing clone(), creating a copy constructor, or writing your own deepCopy() method or something like that that returns a deep copy of the object it's called on. Which one you use is up to you.

Copy constructors are constructors which take an instance of the same object as the argument. Generally copy constructors would just deep copy all fields from the passed object to the newly constructed one, and so are pretty easy to implement.

deepCopy() or other such methods would be implemented in a similar way.

I've heard varying things about Java's clone() method and I usually lean towards other methods of performing a deep copy, but that you can implement by implementing the Cloneable interface and properly implementing the clone() method

awksp
  • 11,764
  • 4
  • 37
  • 44