gpt4 book ai didi

java - 为什么 Collections.copy 操作适用于列表的大小而不是列表的容量?

转载 作者:行者123 更新时间:2023-11-30 06:50:32 24 4
gpt4 key购买 nike

下面是我试过的代码:

//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);

但是复制操作因 IndexOutOfBoundsOperation 而失败。
原因:- 源不适合目标。

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

最佳答案

根据documentation :

复制

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.

抛出

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.

好吧……这正是我们想要的行为。如果您想将一个列表的所有元素添加到另一个列表,您可以List#addAll

关于java - 为什么 Collections.copy 操作适用于列表的大小而不是列表的容量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41281921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com