Arraylist iterators error | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

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.

14th Nov 2018, 8:37 PM
Omar Potoms
Omar Potoms - avatar
2 Answers
+ 1
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
14th Nov 2018, 11:29 PM
Taste
Taste - avatar
0
Ok, Got it. Thank you!
15th Nov 2018, 1:20 PM
Omar Potoms
Omar Potoms - avatar