0

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));
2
  • 1
    IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size()) Commented Jan 26, 2014 at 19:26
  • 1
    I think you misunderstood how a for each loop works. i is not the index, it's the int value hold by each Integer object during the iteration. I.e if your list contains 4,-5,12, i will be equals to 4 (iteration 1), -5(iteration 2) and 12(iteration 3). Commented Jan 26, 2014 at 19:26

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.