How do I copy a java.util.List
into another java.util.List
correctly?
I have a List<SomeBean>
populated from a web service, and I need to use java copy list functionality to clone its contents into a new empty list of the same type. A Google search suggested using Collections.copy()
, but it requires the destination list to have the exact number of elements, which isn’t feasible for my case.
I attempted:
List<SomeBean> wsList = app.allInOne(template);
List<SomeBean> wsListCopy = new ArrayList<SomeBean>(wsList.size());
Collections.copy(wsListCopy, wsList);
System.out.println(wsListCopy.size());
This resulted in an IndexOutOfBoundsException
. I also tried wsListCopy = wsList.subList(0, wsList.size())
, but it later caused a ConcurrentModificationException
.
What is the correct way to copy an entire list without manually iterating over it?
You’re absolutely right—Collections.copy() isn’t what you want here because it requires a pre-sized list. The easiest way to copy a list is by using the ArrayList constructor:
List wsListCopy = new ArrayList<>(wsList);
Creates a new list with the same elements
Independent copy (modifying wsListCopy won’t affect wsList)
Fast and simple
This works perfectly for shallow copies (when objects inside the list don’t need to be copied deeply).
That constructor works well, but if you want more control—like creating an immutable copy or transforming objects—you might prefer Java 8 Streams:
List<SomeBean> wsListCopy = wsList.stream()
.collect(Collectors.toList());
Works the same as the constructor, but lets you apply transformations if needed.
If you want an immutable copy, use:
List<SomeBean> wsListCopy = List.copyOf(wsList);
(
List.copyOf() makes an unmodifiable copy, so you can’t modify wsListCopy later.)
Both of those solutions only create a new list but still reference the same objects inside it. If you need a deep copy (where each object inside the list is cloned too), you should implement copy constructors or use serialization:
List<SomeBean> wsListCopy = wsList.stream()
.map(SomeBean::new) // Assuming SomeBean has a copy constructor
.collect(Collectors.toList());
Ensures each object inside the list is cloned, preventing unintended modifications.
Best for lists of mutable objects that need full independence.