Possible Duplicate:
How to clone ArrayList and also clone its contents?
trying to make a copy of an ArrayList. The underlying object is simple containing on Strings, ints, BigDecimals, Dates and DateTime object. How can I ensure that the modifications made to new ArrayList are not reflected in the old ArrayList?
Person morts = new Person("whateva"); List<Person> oldList = new ArrayList<Person>(); oldList.add(morts); oldList.get(0).setName("Mortimer"); List<Person> newList = new ArrayList<Person>(); newList.addAll(oldList); newList.get(0).setName("Rupert"); System.out.println("oldName : " + oldList.get(0).getName()); System.out.println("newName : " + newList.get(0).getName());
Cheers, P
Deep copy of Java class. In Java, to support deep copy, we must override the clone() of model classes. In clone() method, we must ensure that when somebody invokes object. clone() method then it must return a deep copy of that model class (e.g. Employee class).
ArrayList clone() method is used to create a shallow copy of the list. In the new list, only object references are copied. If we change the object state inside the first ArrayList, then the changed object state will be reflected in the cloned ArrayList as well.
The Java ArrayList clone() method makes the shallow copy of an array list. Here, the shallow copy means it creates copy of arraylist object. To learn more on shallow copy, visit Java Shallow Copy. Here, arraylist is an object of the ArrayList class.
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) { newList.add(p.clone()); }
Assuming clone
is correctly overriden inPerson
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With