Working with Collections.copy

There is a static method named “copy” in the java.util.Collections class. I had never used this method till now and for some code I was writing I just needed to copy a collection to check something, while the “source” collection could change. I needed to check the collection at “this specific point”.

The javadoc for this method is like this,

Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.

So I decided to write my code like this,

List<String> sourceCollection = new ArrayList<String>();

sourceCollection.add("element1");

sourceCollection.add("element2");

List<String> destCollection = new ArrayList<String>(sourceCollection.size());

Looks ok ? Expect it to work? Unfortunately it won’t. You get anIndexOutOfBoundsException with the message – if the destination list is too small to contain the entire source List

Strange? I thought so too, but after further analysis I knew what was wrong. This line of code should give you the answer,

List<String> destCollection = new ArrayList<String>(sourceCollection.size());

This does create a new list, but there is a catch. It’s “initial capacity” is 3, but the “size” is still 0. As a result, although you thought it would work it will not.

They way to fix this this unfortunately like below,

List<String> destCollection = new ArrayList<String>(sourceCollection);

The above statement copies the data from one collection to another, it’s a shallow copy. Then you call the below code to achieve what you really want to, which after looking at the code of Collections is again a shallow copy !!!

Collections.copy(destCollection, sourceCollection);

The only positive thing about this is, it doesn’t allocate new memory and you can reuse the memory.

Learning from this,

  • Collections.copy is not really useful
  • The javadoc is also not clear and that doesn’t help at all
  • If you really want deep copies, iterate and clone each object and put it in the collection
Advertisements

One thought on “Working with Collections.copy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s