Amit Bhati
Amit Bhati

Reputation: 5649

Why Collections.copy operation works on size of list instead of capacity of list?

Below is the code, which I tried:

//Initialized the first list with initial capacity 2
List<String> list1=new ArrayList<String>(2);
list1.add("banana");
list1.add("apple");

//Initialized the second list with initial capacity 4
List<String> list2=new ArrayList<String>(4);

//Performing copying
Collections.copy(list2, list1);

But copying operation failed with IndexOutOfBoundsOperation.
Reason :- source does not fit in dest.

Question why copy operation is working on size i.e. no of elements in a list? Why it doesn't operate on capacity?

Upvotes: 2

Views: 409

Answers (2)

xenteros
xenteros

Reputation: 15852

According to the documentation:

copy

Copies 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. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected. This method runs in linear time.

throws

IndexOutOfBoundsException - if the destination list is too small to contain the entire source List. UnsupportedOperationException - if the destination list's list-iterator does not support the set operation.

So well... it's just the desired behavior. In case you want to add all elements of one list to another, you can List#addAll.

Upvotes: 4

Eran
Eran

Reputation: 393936

public static <T> void copy(List<? super T> dest, List<? extends T> src)

This method is supposed to work for any two List implementations.

What if you run it with :

List<String> l1 = Arrays.asList("a","b","c");
List<String> l2 = Arrays.asList("1","2");
Collections.copy(l1,l2);

Collections.copy can't use add to increase the size of l2, since Arrays.asList returns a fixed size List and doesn't support add. Therefore the size of l2 must be large enough to fit all the elements of l1.

Therefore, looking at the implementation, you'll see that Collections.copy uses set and not add.

Upvotes: 0

Related Questions