gpt4 book ai didi

java - 无法使用 Collections.copy() 方法将数据从一个列表复制到另一个列表

转载 作者:行者123 更新时间:2023-11-29 06:56:03 26 4
gpt4 key购买 nike

我正在尝试使用 Collections.copy 方法将一个列表数据复制到另一个列表数据,但它给我 IndexOutofBoundsException 异常。

源代码:

public static void main(String[] args) {
List<Integer> odds = Arrays.asList(1, 3, 5, 7, 9);
System.out.println("odds = " + odds);

//copy data from one to another using copy() method
List<Integer> anotherOdd = new ArrayList<>(odds.size());
Collections.copy(anotherOdd, odds);
System.out.println("anotherOdd = " + anotherOdd);
}

odds = [1, 3, 5, 7, 9]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
at java.util.Collections.copy(Unknown Source)
at com.study.java.collections.Main.main(Main.java:7)

请指导。

最佳答案

Collections.copy仅在您已经有两个相同大小的列表时使用。注意这句话来自 Collections.copy Java文档:

The destination list must be at least as long as the source list.

你的 anotherOdd列表有容量 odds.size()大小 0。new ArrayList<>(odds.size()) 行只是给出了 ArrayList 多长时间的估计将是,这实际上并不意味着列表具有该大小。

但解决方案很简单:只需使用 anotherOdd.addAll(odds) ,甚至更好,只写 List<Integer> anotherOdd = new ArrayList<>(odds) .

关于java - 无法使用 Collections.copy() 方法将数据从一个列表复制到另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33903237/

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