How to copy Java Collections list How to copy Java Collections list java java

How to copy Java Collections list


b has a capacity of 3, but a size of 0. The fact that ArrayList has some sort of buffer capacity is an implementation detail - it's not part of the List interface, so Collections.copy(List, List) doesn't use it. It would be ugly for it to special-case ArrayList.

As tddmonkey has indicated, using the ArrayList constructor which takes a collection is the way to in the example provided.

For more complicated scenarios (which may well include your real code), you may find the collections within Guava useful.


Calling

List<String> b = new ArrayList<String>(a);

creates a shallow copy of a within b. All elements will exist within b in the exact same order that they were within a (assuming it had an order).

Similarly, calling

// note: instantiating with a.size() gives `b` enough capacity to hold everythingList<String> b = new ArrayList<String>(a.size());Collections.copy(b, a);

also creates a shallow copy of a within b. If the first parameter, b, does not have enough capacity (not size) to contain all of a's elements, then it will throw an IndexOutOfBoundsException. The expectation is that no allocations will be required by Collections.copy to work, and if any are, then it throws that exception. It's an optimization to require the copied collection to be preallocated (b), but I generally do not think that the feature is worth it due to the required checks given the constructor-based alternatives like the one shown above that have no weird side effects.

To create a deep copy, the List, via either mechanism, would have to have intricate knowledge of the underlying type. In the case of Strings, which are immutable in Java (and .NET for that matter), you don't even need a deep copy. In the case of MySpecialObject, you need to know how to make a deep copy of it and that is not a generic operation.


Note: The originally accepted answer was the top result for Collections.copy in Google, and it was flat out wrong as pointed out in the comments.


Just do:

List a = new ArrayList(); a.add("a"); a.add("b"); a.add("c"); List b = new ArrayList(a);

ArrayList has a constructor that will accept another Collection to copy the elements from