Foreach loop
This page documents the results from the foreach whiteboard where all Javapolis 2006 participants were encouraged to participate with their ideas.
Accessing the index and removing an element
This idea was to add an optional part to the syntax of foreach to allow access to the index and iterator remove method.
for (Person p : personList : it) {
...
it.index() it.remove() }
The additional syntax is an optional third part of the foreach loop declaration which returns an object (not Iterator) with index(), remove() and hasNext() methods.
Comments included:
- "Nice idea, do we need it in the loop? Could just manually create the loop index"
- "Problem is that in the manual approach, the loop index leaks and is available for use after the block is complete"
- "Had the foreach loop been considered more carefully we probably wouldn't be having this discussion! However, we appear to be stuck with it. Rather than trying to make it simpler or easier by addition, perhaps we should make ordinary for loops and iteration easier?"
A straw poll vote was taken on this issue - Should Jthe foreach loop be enhanced to support index and remove?
Accessing maps - syntax one
This idea was to add an optional part to the syntax of foreach to allow access to get and set the map entry.
for (String key : personMap : it) {
...
it.getKey() it.getValue() it.setValue(p2) }
The additional syntax is an optional third part of the foreach loop declaration which returns an object (not Iterator) with getKey(), getValue() and setValue() methods.
Comments included:
- "Heh?"
- "Aren't you making the compiler/JVM dependent on the API/libraries"
- "Yes, but it already is - Iterable, StringBuffer, ..."
Accessing maps - syntax two
This idea was to allow two elements to be defined on the left half of the foreach definition.
for (String key, Person value : personMap) {
}
The additional syntax is to allow both the key and value to be assigned when a map is being iterated over.
Comments included: