Java:为什么不能迭代迭代器?

2022-01-10 00:00:00 iterable iterator java

我阅读了 为什么 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);
  }
}

推荐答案

但我仍然不明白为什么这个 [...] 无法实现.

我可以看到几个原因:

  1. Iterator 不可重用,因此 for/each 会消耗迭代器 - 也许不是不正确的行为,但对于那些不知道如何减少 for/each 糖分的人来说是不直观的.
  2. Iterator 不会经常在代码中裸露",因此这会使 JLS 变得复杂而收益甚微(for/each 结构本身就已经够糟糕了,两者都适用Iterables 和数组).
  3. 有一个简单的解决方法.仅仅为此分配一个新对象似乎有点浪费,但是分配很便宜,并且在大多数情况下,逃逸分析甚至可以消除您的小成本.(不过,为什么他们没有在 Iterables 实用程序类中包含这种解决方法,类似于 CollectionsArrays,我无法理解.)
  4. (可能不是真的 - 请参阅评论.)我似乎记得 JLS 只能引用 java.lang[需要引用] 中的内容,所以他们必须在 java.lang 中创建一个 Iterator 接口,该接口 java.util.Iterator 扩展而不添加任何内容.现在我们有两个功能等效的迭代器接口.50% 使用裸迭代器的新代码将选择 java.lang 版本,其余使用 java.util 中的版本.随之而来的是混乱,兼容性问题比比皆是,等等.
  1. 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.
  2. 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).
  3. There's an easy workaround. It may seem a little wasteful to allocate a new object just for this, but allocation is cheap as it is and escape analysis would rid you even of that small cost in most cases. (Why they didn't include this workaround in an Iterables utility class, analogous to Collections and Arrays, is beyond me, though.)
  4. (Probably not true - see the comments.) I seem to recall that the JLS can only reference things in 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.

相关文章