Arraylist loses reference after leaving conditional

"The iterator is smarter than it may appear: remove() removes the last element returned by the iterator. As you can see, it did just what we wanted it to do :)" But the last one is "Fluffy" not "Messi". And if this is true that means that "if instruction" is unnecessary beacause Iterator doesent search for "Lionel Messi" but simply remove last element from ArrayList

l.jargielo Level 18, Poland, Poland 2 January 2023

Is thera a mistake in the last number of index? Cat[] cats = new Cat[4]; cats[0] = new Cat("Thomas"); cats[1] = new Cat("Behemoth"); cats[2] = new Cat("Lionel Messi"); cats[2] = new Cat("Fluffy");

Molo Level 41, Jacksonville, Dania 10 September 2022

Pamiętajcie o "remove()" iteratora bo później się człowiek zastanawia jak usunąć element :] przy zadaniu przydaje się które będzie dalej

Rafał Papała Level 22, Gdańsk, Poland 8 September 2022 My solution to moving null element to the end of array:
 for (int i = 0; i < cats.length - 1; i++) < Cat temp = null; // temporary value for moving null if(cats[i] == null) < cats[i] = cats[i + 1]; // replaces index i (with null) with next index without null cats[i + 1] = temp; // swap next index value with null >> 
 Cat[] cats = new Cat[4]; cats[0] = new Cat("Thomas"); cats[1] = new Cat("Behemoth"); cats[2] = new Cat("Lionel Messi"); cats[3] = new Cat("Fluffy"); cats[1] = null; 
1 August 2021

Just to recap, the for-each loop throws a ConncurrentModificationException when an element of a collection is iterated and deleted at the same time. This is because the for-each loop uses an Iterator internally. To avoid the exception we would need to use this Iterator to remove the element, but it is not visible "outside" and therefore not usable by us users of this loop. Using a regular loop is still possible. You just need to manage the index yourself.

 for (int i = 0; i < cats.size();) if (cats.get(i).name.equals("Behemoth")) cats.remove(cats.get(i)); else i++;