A.Bohlund
A.Bohlund

Reputation: 195

Need a copy of an ArrayList with copies of the objects too

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!

Upvotes: 1

Views: 58

Answers (1)

Matthew
Matthew

Reputation: 7590

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.

Upvotes: 1

Related Questions