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!

5
  • 1
    Have you read the explanations given here stackoverflow.com/questions/689370/… ? Commented Jan 2, 2016 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? Commented Jan 2, 2016 at 10:19
  • A shallow copy, by definition, contains references to the same objects. Commented Jan 2, 2016 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. Commented Jan 2, 2016 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. Commented Jan 2, 2016 at 10:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.