Why doesn't Collections.copy increase destination size?

I am 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 it, but I do not understand:

When I add items manually, the list will automatically increase capacity. Why can't copy # copy do this?

+4
source share
6 answers

Because the way 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 auto-increment, then write your own method.

+3
source

StinePike fooobar.com/questions/1528526/...: . , for,

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

: , - Collection#addAll(Collection) -

dest.addAll(src);
+3

Collections#copy() - , List. . , , ArrayList(Collection), . , ArrayList, , . List. , .

, , .

+3

Collection.copy, ,

, set(int). set(int) , ( add(Object), , ).

, add(Object) , dest , ( src) dest, copy ( @ )

Therefore, the method throws an exception if the mailing list is no longer than the list of sources

+1
source

Suppose that the size is Listresized and Collections.copy()does not assume that this theoretically extends the purpose of this class to all classes that implement the interface Listinstead of resized.

-1
source

All Articles