Arraylist iterators error | Sololearn: Learn to code for FREE!


Arraylist iterators error

Hi all, i've got an issue when I try to remove an element from an ArrayList during an iterator, the code is: for (int i: array) {if (i == x) { array.remove(i); *the compiler check the error here System.out.println("Elemento" + x + " rimosso dalla posizione: " + i); break; } else System.out.println("Non esiste questo elemento"); The error is: Exception in thread "main" java.lang.IndexOutOfBoundsException My question is, can I remove an element using a iterator like: for ( i : array) {} ? Thank you.

11/14/2018 8:37:02 PM

Omar Potoms

2 Answers

New Answer


Oh you cant do it like that, here is why for example you have an arraylist with data {5,6,9} then using foreach loop like that for(int i : x) In foreach i become the value in x each iteration, so at the first iteration i is 5, now you try to remove it with remove() method which take an index as parmeter. That means x.remove(5); its out of bounds, the size of x is 3 but i try to remove the 6th element. That's why i throw an error To resolve this you can use the traditional for loop Or get the index first by using indexOf() method


Ok, Got it. Thank you!