I am new to Java and trying to learn about collections. When I try to copy one ArrayList to another, I run into exceptions. Please find below the code for the same.
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);
}
}
}
}
Exception: Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest at java.util.Collections.copy(Unknown Source) at ArrayListTest.main(ArrayListTest.java:19)
Please let me know, if I am doing something wrong.