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

Nit*_*tal 1 java collections arraylist

我试图使用Collections.copy方法将一个List数据复制到另一个,但它给了我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)
Run Code Online (Sandbox Code Playgroud)

请指导.

Lou*_*man 5

Collections.copy仅适用于已有两个相同大小的列表的情况.请注意Collections.copyJavadoc中的这句话:

目标列表必须至少与源列表一样长.

你的anotherOdd列表有容量, odds.size()大小为0.该行new ArrayList<>(odds.size())只是估计了它的长度ArrayList,它实际上并不意味着列表具有该大小.

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