D
D
DerKote2016-08-25 06:26:24
Java
DerKote, 2016-08-25 06:26:24

Why is remove forbidden in for/in?

All sources simply indicate this limitation, but the reason is not indicated, and for me it is not obvious. Requires explicit use of Iterator. Why can't you do this:

public void remove(Set<Cat> cats) {
for (Cat cat : cats) 
    cats.remove(cat);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2016-08-25
@leahch

Because you're cutting the branch you're sitting on.

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();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question