在Java中复制Arraylist时出现异常

时间:2017-07-21 05:21:10

标签: java arraylist

我是Java的新手,并试图了解集合。当我尝试将一个ArrayList复制到另一个时,我遇到异常。请在下面找到相同的代码。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class ArrayListTest {

    public static void main(String[] args) {

        try(Scanner scanner = new Scanner(System.in) ){
            System.out.println("Enter the number of elements to enter into an array");
            int userCount = scanner.nextInt();
            System.out.println("Enter the number one by one");
            ArrayList<Integer> arrayList = new ArrayList<>();
            ArrayList<Integer> destinationList = new ArrayList<>(arrayList);
            for(int i=0; i<userCount; i++){
                arrayList.add(scanner.nextInt());
            }

            Collections.copy(destinationList, arrayList);           
            //Print elements in the Array List
            for(Integer number: destinationList){
                System.out.println("The numbers are");
                System.out.println(number);
            }

        }

        }
}

例外: 线程&#34; main&#34;中的例外情况java.lang.IndexOutOfBoundsException:Source不适合dest     在java.util.Collections.copy(未知来源)     在ArrayListTest.main(ArrayListTest.java:19)

如果我做错了,请告诉我。

2 个答案:

答案 0 :(得分:1)

我修复你的代码,试试这个:

try (Scanner scanner = new Scanner(System.in)) {
        System.out.println("Enter the number of elements to enter into an array");
        int userCount = scanner.nextInt();
        System.out.println("Enter the number one by one");
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int i = 0; i < userCount; i++) {
            arrayList.add(scanner.nextInt());
        }

        ArrayList<Integer> destinationList = new ArrayList<>(arrayList);
        // Print elements in the Array List
        for (Integer number : destinationList) {
            System.out.println("The numbers are");
            System.out.println(number);
        }

}

此行将arrayList复制到目的地列表中:

ArrayList<Integer> destinationList = new ArrayList<>(arrayList);

答案 1 :(得分:0)

复制方法需要目标的大小与要复制的列表相同或更大。默认情况下,arrayList的大小会随着添加更多元素而增加。您需要检查arraylist的大小,然后创建具有相同或更大大小的目标列表以避免此异常。