top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is meant by Collections.copy in Java?

+2 votes
324 views
What is meant by Collections.copy in Java?
posted Jun 8, 2015 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

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 everything
List<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.

answer Jun 8, 2015 by Amit Kumar Pandey
+1 vote

There are two ways to copy a source list to a destination list. One way is to use ArrayList constructor

ArrayList dstList = new ArrayList(srcList);

The other is to use Collections.copy() (as below). Note the first line, we allocate a list at least as long as the source list, because in the javadoc of Collections, it says The destination list must be at least as long as the source list.

ArrayList<Integer> dstList = new ArrayList<Integer>(srcList.size());
Collections.copy(dstList, srcList);

Both methods are shallow copy. So what is the difference between these two methods?

First, Collections.copy() won't reallocate the capacity of dstList even if dstList does not have enough space to contain all srcList elements. Instead, it will throw an IndexOutOfBoundsException. One may question if there is any benefit of it. One reason is that it guarantees the method runs in linear time. Also it makes suitable when you would like to reuse arrays rather than allocate new memory in the constructor of ArrayList.

Collections.copy() can only accept List as both source and destination, while ArrayList accepts Collection as the parameter, therefore more general.

answer Jun 11, 2015 by Manikandan J
...