1

Here is my code :

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
        arrayLists.get(0).add(100);
        arrayLists.get(0).add(50);
        arrayLists.get(1).add(67);
        System.out.println(arrayLists.get(0).get(0));
    }
}

And this is the error message:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Main.main(Main.java:6)

I didnt understand the problem.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Mert Yanık
  • 164
  • 1
  • 1
  • 9
  • `arrayLists.add(new ArrayList()); arrayLists.add(new ArrayList());` The exception tell you you tried to get an item in the list at index 0 but the list have a size of 0 (empty). a list of list (`List`) is just an empty `List` waiting for `List` instance to be added in;: – AxelH Apr 11 '18 at 19:41
  • Since this is correctly answered, the duplicate can give you a complet explanation about the exception itself. – AxelH Apr 11 '18 at 19:46

3 Answers3

3

You create a List of List but you never create instance of inner List so there is nothing to take, you have to :

ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
arrayLists.add(new ArrayList<Integer>());
arrayLists.get(0).add(100);
arrayLists.get(0).add(50);

arrayLists.add(new ArrayList<Integer>());
arrayLists.get(1).add(67);

System.out.println(arrayLists.get(0).get(0));   // 100
System.out.println(arrayLists.get(0).get(1));   //  50
System.out.println(arrayLists.get(1).get(0));   //  67
azro
  • 53,056
  • 7
  • 34
  • 70
1

You are missing the ArrayList inside the ArrayList. Change your code to

ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
arrayLists.add(new ArrayList<Integer>());
arrayLists.add(new ArrayList<Integer>());
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
1

Both above solutions gives you an idea about your problem, In case You you want to add multiple ArrayList in one shot, you can use ArrayList::addAll like this :

List<ArrayList<Integer>> arrayLists = new ArrayList<>();
arrayLists.addAll(Arrays.asList(
        Lists.newArrayList(100, 50),
        Lists.newArrayList(67)
));

Or in one shot :

List<ArrayList<Integer>> arrayLists = new ArrayList<>(Arrays.asList(
        Lists.newArrayList(100, 50),
        Lists.newArrayList(67)
));

The List.newArrayList(..) is from Guava.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140