gpt4 book ai didi

java - 增强的 for 循环不接受 Iterator

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:35 25 4
gpt4 key购买 nike

如果之前有人问过这个问题,请原谅。我的搜索没有提出任何其他类似的问题。这是让我在 Java 中感到惊讶的事情。

显然,增强的 for 循环只接受 java.lang.Iterable 的数组或实例。 .它不接受 java.util.Iterator作为迭代的有效对象引用。例如,Eclipse 显示以下代码的错误消息。它说:“只能迭代数组或 java.lang.Iterable 的实例

Set<String> mySet = new HashSet<String>();
mySet.add("dummy");
mySet.add("test");
Iterator<String> strings = mySet.iterator();
for (String str : strings) {
// Process str value ...
}

为什么会这样?我想知道为什么增强的 for 循环被设计为以这种方式工作。尽管 Iterator 不是集合,但它可用于从集合中一次返回一个元素。请注意,java.lang.Iterable 中的唯一方法界面是Iterator<T> iterator()返回 Iterator .在这里,我直接递给它一个Iterator。 .我知道 hasNext()next()可以使用,但使用增强的 for 循环使它看起来更干净。

我现在明白的一件事是我可以直接在 mySet 上使用增强的 for 循环.所以我什至不需要额外的电话来获得 Iterator .所以,这就是编写代码的方式,是的 - 它确实有一定道理。

最佳答案

增强的 for 循环是 JSR 201 的一部分.从该页面,您可以下载建议的最终草案文件,其中包括直接解决您的问题的常见问题解答部分:

Appendix I. Design FAQ

  1. Why can't I use the enhanced for statement with an Iterator (rather than an Iterable or array)?

Two reasons: (1) The construct would not provide much in the way on syntactic improvement if you had an explicit iterator in your code, and (2) Execution of the loop would have the "side effect" of advancing (and typically exhausting) the iterator. In other words, the enhanced for statement provides a simple, elegant, solution for the common case of iterating over a collection or array, and does not attempt to address more complicated cases, which are better addressed with the traditional for statement.

  1. Why can't I use the enhanced for statement to:
    • remove elements as I traverse a collection ("filtering")?
    • simultaneously iterate over multiple collections or arrays?
    • modify the current slot in an array or list?

See Item 1 above. The expert group considered these cases, but opted for a simple, clean extension that dose(sic) one thing well. The design obeys the "80-20 rule" (it handles 80% of the cases with 20% of the effort). If a case falls into the other 20%, you can always use an explicit iterator or index as you've done in the past.

换句话说,委员会选择限制提案的范围,而一些人们可以想象成为提案一部分的功能并没有被削减。

关于java - 增强的 for 循环不接受 Iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31348033/

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