Skip to content
Advertisement

Tag: foreach

Idiomatic way to use for-each loop given an iterator?

When the enhanced for loop (foreach loop) was added to Java, it was made to work with a target of either an array or Iterable. That works great for Collection classes that only implement one type of iteration, and thus have a single iterator() method. But I find myself incredibly frustrated the odd time I want to use a non-standard

How does the Java ‘for each’ loop work?

Consider: What would the equivalent for loop look like without using the for each syntax? Answer Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred. As was noted by Denis Bueno, this code works

Advertisement