JEP286 - Use of Indexes in enhanced for-loop

111 Views Asked by At

I was reading up the documentation for Local-Variable Type Inference at the below Open JDK link.

http://openjdk.java.net/jeps/286

One thing caught my eye - "indexes in the enhanced for-loop". I looked up SO and don't see where indexes in enhanced for loop are discussed. My understanding so far has been that indexes are only allowed in traditional for loops (Clearly, i am missing something).

Can you please provide some examples for use of indexes in enhanced for-loop?

Goals

We seek to improve the developer experience by reducing the ceremony associated with writing Java code, while maintaining Java's commitment to static type safety, by allowing developers to elide the often-unnecessary manifest declaration of local variable types. This feature would allow, for example, declarations such as:

var list = new ArrayList<String>();  // infers ArrayList<String>
var stream = list.stream();          // infers Stream<String>

This treatment would be restricted to local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop; it would not be available for method formals, constructor formals, method return types, fields, catch formals, or any other kind of variable declaration.

2

There are 2 best solutions below

0
Naman On BEST ANSWER

If you further look at the style guidelines linked in the same document, you can find a good suggestion of using iterator under "Examples" with the local variable such as:

void removeMatches(Map<? extends String, ? extends Number> map, int max) {
    for (var iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
        var entry = iterator.next();
        if (max > 0 && matches(entry)) {
            iterator.remove();
            max--;
        }
    }
}

Further for the indexes part specifically, you can also do something like:

void removeMatchesIndexes(List<? extends Number> list, int max) {
    for (var i = 0; i < list.size(); i++) {
        var entry = list.get(i);
        if (entry.intValue() > max) {
            list.remove(entry);
        }
    }
}
0
Dorian Gray On

This is referring to the variable declared withing the enhanced for loop, such as:

var elements = new Arraylist<String>();
// Fill the list
for (var element : elements) {
    // element is type String
}