Will
Will

Reputation: 89

adding arrayList to arraylist using loop

Whenever i try and run my code i get an error array out of bounds.

    trans = new ArrayList<List<Transition>>(5);
    ArrayList<Transition> t = new ArrayList<Transition>(5);
    for (j = 0; j <5; j++)
        trans.get(j).addAll(t); // <- Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

Upvotes: 0

Views: 77

Answers (3)

SMA
SMA

Reputation: 37023

You have an empty list of size 0 when you create your list of lists and then you say get(i) which will try to compare size with i and jdk expect size to be greater than the index i.

So probably you could do something like:

trans = new ArrayList<List<Transition>>(5);
for (j = 0; j <5; j++) {
   trans.add(new ArrayList<Transition>()); 
}
ArrayList<Transition> t = new ArrayList<Transition>(5);
for (j = 0; j <5; j++)
    trans.get(j).addAll(t); // <- out of bounds

Upvotes: 4

MihaiC
MihaiC

Reputation: 1583

Your trans list is empty. You didn't add anything to it. When you run trans.get(j) it can't get anything.

Upvotes: 1

Maroun
Maroun

Reputation: 95968

See the docs:

Constructs an empty list with the specified initial capacity.

You didn't add anything, you cannot get:

 trans.get(j).addAll(t);
       ↑ 

Try to check the size, you'll get 0. So any attempt to access the trans will throw an exception.

Upvotes: 0

Related Questions