@DerKote

Почему запрещен remove в for/in?

Во всех источниках просто указано данное ограничение, но причина не указана, и для меня она не очевидна. Требуют явно использовать Iterator. Почему нельзя делать так:
public void remove(Set<Cat> cats) {
for (Cat cat : cats) 
    cats.remove(cat);
}
  • Вопрос задан
  • 254 просмотра
Пригласить эксперта
Ответы на вопрос 1
leahch
@leahch
3D специалист. Dолго, Dорого, Dерьмово.
Потому что вы режете сук, на котором сидите.
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.


List<String> names = ....
Iterator<String> i = names.iterator();
while (i.hasNext()) {
   String s = i.next(); // must be called before you can call i.remove()
   // Do something
   i.remove();
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы