Java 中增强的 for 循环和迭代器的优点是什么? [英] What are the Advantages of Enhanced for loop and Iterator in Java?

查看:36
本文介绍了Java 中增强的 for 循环和迭代器的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我Java +5中增强的for循环和迭代器的优点是什么?

can anyone please specify to me what are the advantages of Enhanced for loop and Iterators in java +5 ?

推荐答案

Stephen Colebourne(Joda-Time、JSR-310 等)增强每个循环迭代控制 在 Java 7 中扩展它的提议:

The strengths and also the weaknesses are pretty well summarized in Stephen Colebourne (Joda-Time, JSR-310, etc) Enhanced for each loop iteration control proposal to extend it in Java 7:

扩展 Java 5 for-each 循环以允许访问循环索引,这是否是第一个或最后一次迭代,并删除当前项目.

FEATURE SUMMARY:

Extends the Java 5 for-each loop to allow access to the loop index, whether this is the first or last iteration, and to remove the current item.

for-each 循环几乎肯定是最新的来自 Java 5 的流行特性.它有效因为它增加了抽象水平 - 而不是必须表达如何循环的底层细节围绕列表或数组(带有索引或迭代器),开发人员只需声明他们想要循环并且语言负责其余的工作.然而,所有的好处都失去了一旦开发人员需要访问索引或删除项目.

The for-each loop is almost certainly the most new popular feature from Java 5. It works because it increases the abstraction level - instead of having to express the low-level details of how to loop around a list or array (with an index or iterator), the developer simply states that they want to loop and the language takes care of the rest. However, all the benefit is lost as soon as the developer needs to access the index or to remove an item.

每个工作的原始 Java 5相对保守的立场旨在解决的问题的数量80% 的情况.然而,循环是这样的编码中的常见形式剩下的 20% 没有解决代表重要的代码体.

The original Java 5 for each work took a relatively conservative stance on a number of issues aiming to tackle the 80% case. However, loops are such a common form in coding that the remaining 20% that was not tackled represents a significant body of code.

转换循环的过程从每个要索引或基于迭代器是痛苦的.这是因为旧的循环风格如果明显更低,更多冗长且不太清楚.也是痛苦,因为大多数 IDE 不支持这种去重构".

The process of converting the loop back from the for each to be index or iterator based is painful. This is because the old loop style if significantly lower-level, is more verbose and less clear. It is also painful as most IDEs don't support this kind of 'de-refactoring'.

一个常见的编码习惯用语表示为比现在更高的抽象.这有助于可读性和清晰度.

A common coding idiom is expressed at a higher abstraction than at present. This aids readability and clarity.

...

总而言之,增强的 for 循环提供了一种简洁的高级语法来循环列表或数组,从而提高了清晰度和可读性.但是,它遗漏了一些部分:允许访问索引循环或删除项目.

To sum up, the enhanced for loop offers a concise higher level syntax to loop over a list or array which improves clarity and readability. However, it misses some parts: allowing to access the index loop or to remove an item.

这篇关于Java 中增强的 for 循环和迭代器的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆