getting Exception in thread "main" java.lang.IndexOutOfBoundsException error while adding elements to the list using scanner

Viewed 24

I am trying to create multiple array list

I need to ask user the number of times he wants to create arraylist

The length of each array list

The elements of each array list

Input example:

2 (which indicates user wants to create 2 list)

3 (which indicates in first list user wants to add 3 items)

1 (1st item to be added in first list) 2 (2nd item to be added in first list) 3 (3rd item to be added in first list)

2 (which indicates in second list user wants to add 2 items)

1 (1st item to be added in first list) 2 (2nd item to be added in first list)

public static void main(String[] args) {
        int tcCount = getNoOfTC();
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        for (int i = 0; i < tcCount; i++) {
            System.out.println("Enter the size of the array");
            int len = scanner.nextInt();
            for (int j = 0; j < len; j++) {
                int temp = scanner.nextInt();
                list.get(i).add(temp);
            }
        }
    }

Enter the below Input and you get the error

Enter the number of Test Cases 3

Enter the size of the array 2

1

1 Answers

This line ArrayList<ArrayList<Integer>> list = new ArrayList<>(); creates a variable list but it will be empty. When you are calling list.get(i) on empty list you are getting IndexOutOfBounds exception. To fix this you must fill your list first.

for (int i = 0; i < tcCount; i++) {
   list.add(new ArrayList<Integer>());

should solve your problem.

Related