我阅读了 为什么 Java 的 Iterator 不是 Iterable? 和为什么枚举不能迭代?,但我还是不明白为什么会这样:
I read Why is Java's Iterator not an Iterable? and Why aren't Enumerations Iterable?, but I still don't understand why this:
void foo(Iterator<X> it) {
for (X x : it) {
bar(x);
baz(x);
}
}
无法实现.换句话说,除非我遗漏了什么,否则上述内容可能是很好且有效的语法糖:
was not made possible. In other words, unless I'm missing something, the above could have been nice and valid syntactic sugar for:
void foo(Iterator<X> it) {
for (X x; it.hasNext();) {
x = it.next();
bar(x);
baz(x);
}
}
但我仍然不明白为什么这个 [...] 无法实现.
我可以看到几个原因:
Iterator 不可重用,因此 for/each 会消耗迭代器 - 也许不是不正确的行为,但对于那些不知道如何减少 for/each 糖分的人来说是不直观的.Iterator 不会经常在代码中裸露",因此这会使 JLS 变得复杂而收益甚微(for/each 结构本身就已经够糟糕了,两者都适用Iterables 和数组).Iterables 实用程序类中包含这种解决方法,类似于 Collections 和 Arrays,我无法理解.)java.lang[需要引用] 中的内容,所以他们必须在 java.lang 中创建一个 Iterator 接口,该接口 java.util.Iterator 扩展而不添加任何内容.现在我们有两个功能等效的迭代器接口.50% 使用裸迭代器的新代码将选择 java.lang 版本,其余使用 java.util 中的版本.随之而来的是混乱,兼容性问题比比皆是,等等.Iterators are not reusable, so a for/each would consume the iterator - not incorrect behavior, perhaps, but unintuitive to those who don't know how the for/each is desugared.Iterators don't appear "naked" in code all that often so it would be complicating the JLS with little gain (the for/each construct is bad enough as it is, working on both Iterables and arrays).Iterables utility class, analogous to Collections and Arrays, is beyond me, though.)java.lang[citation needed], so they'd have to create an Iterator interface in java.lang which java.util.Iterator extends without adding anything to. Now we have two functionally equivalent iterator interfaces. 50% of the new code using naked iterators will choose the java.lang version, the rest use the one in java.util. Chaos ensues, compatibility problems abound, etc.我认为第 1-3 点非常符合 Java 语言设计理念的走向:不要让新手感到惊讶,如果没有明显的收益超过成本,不要使规范复杂化, 不要用语言特性来做图书馆可以做的事情.
I think points 1-3 are very much in line with how the Java language design philosophy seems to go: Don't surprise newcomers, don't complicate the spec if it doesn't have a clear gain that overshadows the costs, and don't do with a language feature what can be done with a library.
同样的论点可以解释为什么 java.util.Enumeration 也不是 Iterable.
The same arguments would explain why java.util.Enumeration isn't Iterable, too.
这篇关于Java:为什么不能迭代迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
Java从数组中删除重复项?Java Remove Duplicates from an Array?(Java从数组中删除重复项?)
如何修复调用失败来自服务器的意外响应:在 AnHow to fix Invocation failed Unexpected Response from Server: Unauthorized in Android studio(如何修复调用失败来自服务器的意外响应:在
AES 加密,解密文件中有多余的垃圾字符AES encryption, got extra trash characters in decrypted file(AES 加密,解密文件中有多余的垃圾字符)
AES 错误:给定的最终块未正确填充AES Error: Given final block not properly padded(AES 错误:给定的最终块未正确填充)
在 JAVA 中使用 AES/GCM 检测不正确的密钥Detecting incorrect key using AES/GCM in JAVA(在 JAVA 中使用 AES/GCM 检测不正确的密钥)
Java 中的 AES-256-CBCAES-256-CBC in Java(Java 中的 AES-256-CBC)