简体   繁体   English

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

[英]JEP286 - Use of Indexes in enhanced for-loop

I was reading up the documentation for Local-Variable Type Inference at the below Open JDK link.我在下面的 Open JDK 链接中阅读了本地变量类型推断的文档。

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

One thing caught my eye - " indexes in the enhanced for-loop ".一件事引起了我的注意 - “增强的 for 循环中的索引”。 I looked up SO and don't see where indexes in enhanced for loop are discussed.我查了一下,没有看到在增强 for 循环中的索引被讨论的地方。 My understanding so far has been that indexes are only allowed in traditional for loops (Clearly, i am missing something).到目前为止,我的理解是索引只允许在传统的 for 循环中使用(显然,我遗漏了一些东西)。

Can you please provide some examples for use of indexes in enhanced for-loop?您能否提供一些在增强的 for 循环中使用索引的示例?

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.我们寻求通过减少与编写 Java 代码相关的仪式来改善开发人员体验,同时通过允许开发人员省略通常不必要的局部变量类型的清单声明,同时保持 Java 对静态类型安全的承诺。 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;这种处理将仅限于具有初始值设定项的局部变量、增强的 for-loop 中的索引以及在传统 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.它不适用于方法形式、构造函数形式、方法返回类型、字段、捕获形式或任何其他类型的变量声明。

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

This is referring to the variable declared withing the enhanced for loop, such as:这是指使用增强的 for 循环声明的变量,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM