Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Collections.copy increase the size of the destination?

I'm using the following code:

List<Object> dest = new LinkedList<Object>();
Collections.copy(oldList, src);

When i execute the code, I get an exception:

java.lang.IndexOutOfBoundsException: Source does not fit in dest
    at java.util.Collections.copy(Collections.java:589)

I know how to fix that, but what i don't understand is:

When i add elements manually, the list would increase the capacity automaticly. Why can't Collections#copy do that?

like image 867
Philipp Sander Avatar asked Feb 24 '14 11:02

Philipp Sander


People also ask

How do you duplicate a collection in Java?

The copy() method of java. util. Collections class is used to copy 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.

What is the collections class in java?

Java Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.


2 Answers

As StinePike already said in https://stackoverflow.com/a/21986805 : That's how it is implemented. It is just a convenience method that you can use instead of a for-loop like

for (int i=0; i<src.size(); i++)
{
    dst.set(i, src.get(i));
}

Regarding your question about the automatic size increase: It sounds as if you are actually looking for something like Collection#addAll(Collection) - so in this case

dest.addAll(src);
like image 75
Marco13 Avatar answered Nov 13 '22 00:11

Marco13


Because this is how it is implemented. If you see the source code of this method you will see that

 if (srcSize > dest.size())
    throw new IndexOutOfBoundsException("Source does not fit in dest");

So if you want to implement autoincrement, Then write your own method.

like image 30
stinepike Avatar answered Nov 13 '22 02:11

stinepike