JEP286 - 在增强的 for 循环中使用索引

JEP286 - Use of Indexes in enhanced for-loop

我在下面的 Open JDK link.

阅读了局部变量类型推断的文档

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

有一件事引起了我的注意——“增强的 for 循环中的索引”。我查找了 SO,但没有看到讨论增强 for 循环中的索引的位置。到目前为止,我的理解是索引只允许在传统的 for 循环中使用(显然,我遗漏了一些东西)。

能否提供一些在增强型 for 循环中使用索引的示例?

目标

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.

这是指在增强的for循环中声明的变量,例如:

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

如果您进一步查看同一文档中链接的 style guidelines,您会发现一个很好的建议,即在 "Examples" 下使用迭代器和局部变量,例如:

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

进一步针对索引部分,您还可以执行以下操作:

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