1

Hi I'm trying to create a ArrayList which contains copies of the objects in the original ArrayList. Ive searched here but couldn't understans enough of earlier posts to get helped. Below is the ArrayList Im trying to make a copy of.

ArrayList<Stuff> originallist = new ArrayList<Stuff>();

Sorry if repost!

A.Bohlund
  • 195
  • 1
  • 10
  • 1
    Have you read the explanations given here http://stackoverflow.com/questions/689370/java-collections-copy-list-i-dont-understand ? – wiredolphin Jan 02 '16 at 10:12
  • Now I have read it. If I create a shallow copy, does it only contain references to the same spot in the memory of the objects or does it create copies of all the objects? – A.Bohlund Jan 02 '16 at 10:19
  • A shallow copy, by definition, contains references to the same objects. – JB Nizet Jan 02 '16 at 10:25
  • 1
    How already explained in that post, the built in `Collections.copy` doesn't create a deep copy but a shallow one. To obtain a deep copy, you need to make a new list and afterwards for each element in the old list make a deep copy and finally add it to the new list. – wiredolphin Jan 02 '16 at 10:27
  • Deep copy here means copy the bytes of object x to a new location in memory and get a reference to that newly deep-copied object, just for completeness. – wiredolphin Jan 02 '16 at 10:36

1 Answers1

1

This isn't necessary something that can be answered in general, as it depends on how the objects can be copied.

Supposing that the object has a method called copyOf that returns a copy of the object, you would need to do

ArrayList<Stuff> copy = new ArrayList<Stuff>(originallist.size());
for (Stuff s : originallist) {
    copy.add(s.copyOf());
}

There are many places that the "copyOf" function may come from. If an object implements the cloneable interface, that may be a source of this function (but there are various reasons that the interface is discouraged). Some classes contain a constructor that creates a copy from an existing instance, in which case you could do

ArrayList<Stuff> copy = new ArrayList<Stuff>(originallist.size());
for (Stuff s : originallist) {
    copy.add(new Stuff(s));
}

in other cases, it may have to be done with an approach accessing fields (for example with a Person object that keeps a first and last name)

ArrayList<Person> copy = new ArrayList<Person>(originallist.size());
for (Person s : originallist) {
    copy.add(new Person(s.getFirstName(),s.getLastName()));
}

To be certain of how to do it, you should look at the api guides to the "Stuff" object. The actual copying of the List itself, is easy.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
Matthew
  • 7,440
  • 1
  • 24
  • 49