How do I copy an ArrayList?

Asked 1 years ago, Updated 1 years ago, 108 views

How do I copy ArrayList in Java 1.5?

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ...Copy each item of dogs...

For example, if I want to copy dogs to the clonedList like this, how can I do it?

java collections clone deep-copy

2022-09-21 15:53

1 Answers

public static List<Dog> cloneList(List<Dog> list) {
    List<Dog> clone = new ArrayList<Dog>(list.size());
    for(Dog item: list) clone.add(item.clone());
    return clone;
}

You can do a repeat statement like this and add it to the closed list one by one.


2022-09-21 15:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.