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?
Calling
creates a shallow copy of
awithinb. All elements will exist withinbin the exact same order that they were withina(assuming it had an order).Similarly, calling
also creates a shallow copy of
awithinb. If the first parameter,b, does not have enough capacity (not size) to contain all ofa‘s elements, then it will throw anIndexOutOfBoundsException. The expectation is that no allocations will be required byCollections.copyto 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 ofStrings, which are immutable in Java (and .NET for that matter), you don’t even need a deep copy. In the case ofMySpecialObject, 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.copyin Google, and it was flat out wrong as pointed out in the comments.