简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM