2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Java Collections copy list - I don't understand

I have an ArrayList and I want to copy it exactly. I use utility classes when possible on the assumption that someone spent some time making it correct. So naturally, I end up with the Collections class which contains a copy method.

Suppose I have the following:

List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
List<String> b = new ArrayList<String>(a.size());
Collections.copy(b,a);

This fails because basically it thinks b isn"t big enough to hold a. Yes I know b has size 0, but it should be big enough now shouldn"t it? If I have to fill b first, then Collections.copy() becomes a completely useless function in my mind. So, except for programming a copy function (which I"m going to do now) is there a proper way to do this?

userimage
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 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 is