Adam Tr.
Adam Tr.

Reputation: 9

IndexOutOfBoundsException: with two LinkedList

So am trying to remove a multiple words from a LinkedList from a given indexs on LinkedList as well. But am getting

IndexOutOfBoundsException:

am trying to do that:

    LinkedList<Integer> List_Of_Index = new LinkedList<>();
    LinkedList<String> list_Of_Words = new LinkedList<>();


    List_Of_Index.add(0);
    List_Of_Index.add(2);

    list_Of_Words.add("remove");
    list_Of_Words.add("dont");
    list_Of_Words.add("remove");

    for (int numb:List_Of_Index){
        list_Of_Words.remove(numb);
    }

Upvotes: 1

Views: 40

Answers (3)

Oleg Zinoviev
Oleg Zinoviev

Reputation: 559

After first iteration in cycle yout list of words will have size 2(last index 1)

Upvotes: 0

davidxxx
davidxxx

Reputation: 131486

As you removed one element of the List at the first iteration of the loop, the list that contained two elements contains a single element at the second iteration and referencing the index 2 is not valid.
Whereas list_Of_Words.remove(2) that throws IndexOutOfBoundsException.

You could use a counter to count the number of removal and use it to decrement the index to remove :

 int removal = 0;
 for (int numb:List_Of_Index){
        list_Of_Words.remove(numb-removal);
        removal++;
 }

Upvotes: 3

you can not remove the element at index 2 in the list_Of_Words....
the list_Of_Words has 2 elements only...

Upvotes: 1

Related Questions