-1

I am new to Java. Trying to create 2D arraylist, but getting this indexOutOfBoundsException: Index: 0, Size: 0

ArrayList<ArrayList<Integer>> twoDArrayList = new ArrayList<>();
for (int i = 0; i < 4; i++)
{
    twoDArrayList.add(new ArrayList<>());
    twoDArrayList.get(i).set(0,1); 
}

Why second line fails in the for loop? When i = 0, there is already a row created with add(new ArrayList<>())

------------------------------- thank you for your hints! ---------------------

Now finally I have a solution to print Pascal triangle..... first 5 lines of it

ArrayList> twoDArrayList = new ArrayList<>();

    for (int i=0; i < 5; i++)
    {

        ArrayList<Integer> row = new ArrayList<>();

        for (int j = 0; j <= i ; j++)
        {
            row.add(0);
        }

        row.set(0, 1);
        row.set(i, 1);

        twoDArrayList.add(row);


        for (int j=1; j < i; j++)
        {
            twoDArrayList.get(i).set(j, twoDArrayList.get(i-1).get(j-1) + twoDArrayList.get(i-1).get(j));
        }

    }


    for (ArrayList<Integer> row: twoDArrayList)
    {
        for (Integer element: row)
        {
            System.out.printf("%4d",element);
        }
        System.out.println();
    }
LetzerWille
  • 5,355
  • 4
  • 23
  • 26

4 Answers4

1

You row is created with a empty list.

The value from twoDArray.get(i) will be a list with size 0.

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
0

The arraylist set method does not add objects, but replaces with an object at a specified position.

In your first line of the for loop, you instantiate an empty arraylist. Then in your second line of the for loop, you access the newly instantiated array list and attempt to replace the element in the first position with the integer "1" - which yields a index out of bounds exception, since the first position has no element/null.

BranMoney
  • 21
  • 4
0
ArrayList<ArrayList<Integer>> twoDArrayList = new ArrayList<>();
   for (int i = 0; i < 4; i++)
    {
       ArrayList<Integer> al = new ArrayList<>();
       al.add(i,1);
       twoDArrayList.add(al);
       twoDArrayList.get(i).set(0,1); 
    }
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46
-2
public <T> List<T> twoDArrayToList(T[][] twoDArray) {
    List<T> list = new ArrayList<T>();
    for (T[] array : twoDArray) {
        list.addAll(Arrays.asList(array));
    }
    return list;
}
andrewsi
  • 10,807
  • 132
  • 35
  • 51