简体   繁体   中英

java.lang.IndexOutOfBoundsException for ArrayList

I get an java.lang.IndexOutOfBoundsException for this code.

private List<Integer> LoeschenX = new ArrayList<Integer>();
private List<Integer> LoeschenY = new ArrayList<Integer>();

for (int i : LoeschenY) LoeschenX.add(LoeschenY.get(i));

When you do

for (int i : LoeschenY)

you are looping over the elements of LoeschenY , not on indexes. You may want to iterate over indexes so you can use get(i) :

for (int i = 0; i < LoeschenY.size(); i++) 
    LoeschenX.add(LoeschenY.get(i));

Remember that get(index) will return the value in an specific index.

Edit: You can also try

for (int i : LoeschenY) 
    LoeschenX.add(i);

since i takes the values of the elements of LoeschenY , you will add these values to LoeschenX .

You seem to be iterating over the elements in the Y array, but the get method actually uses the element as an index the way you're doing it.

Try

for(int i : LoeschenY)
    LoeschenX.add(i);

Or

for(int i = 0; i < LoeschenY.size(); i++)
    LoeschenX.add(LoeschenY.get(i));

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