gpt4 book ai didi

java - Java中增强的for循环和迭代器有什么优势?

转载 作者:IT老高 更新时间:2023-10-28 20:39:48 25 4
gpt4 key购买 nike

我想知道 Java +5 中增强的 for 循环和迭代器的优点是什么?

最佳答案

Stephen Colebourne(Joda-Time、JSR-310 等)Enhanced for each loop iteration control 中很好地总结了优点和缺点建议在 Java 7 中扩展它:

FEATURE SUMMARY:

Extends the Java 5 for-each loop to allow access to theloop index, whether this is the firstor last iteration, and to remove thecurrent item.

MAJOR ADVANTAGE

The for-each loop is almost certainly the most newpopular feature from Java 5. It worksbecause it increases the abstractionlevel - instead of having to expressthe low-level details of how to looparound a list or array (with an indexor iterator), the developer simplystates that they want to loop and thelanguage takes care of the rest.However, all the benefit is lost assoon as the developer needs to accessthe index or to remove an item.

The original Java 5 for each work tooka relatively conservative stance on anumber of issues aiming to tackle the80% case. However, loops are such acommon form in coding that theremaining 20% that was not tackledrepresents a significant body of code.

The process of converting the loopback from the for each to be index oriterator based is painful. This isbecause the old loop style ifsignificantly lower-level, is moreverbose and less clear. It is alsopainful as most IDEs don't supportthis kind of 'de-refactoring'.

MAJOR BENEFIT:

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

...

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

另见

关于java - Java中增强的for循环和迭代器有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3328672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com