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?
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With