Why aren't Enumerations Iterable?

被刻印的时光 ゝ 提交于 2019-11-27 23:24:30

Enumeration hasn't been modified to support Iterable because it's an interface not a concrete class (like Vector, which was modifed to support the Collections interface).

If Enumeration was changed to support Iterable it would break a bunch of people's code.

As an easy and clean way of using an Enumeration with the enhanced for loop, convert to an ArrayList with java.util.Collections.list.

for (TableColumn col : Collections.list(columnModel.getColumns()) {

(javax.swing.table.TableColumnModel.getColumns returns Enumeration.)

Note, this may be very slightly less efficient.

It doesn't make sense for Enumeration to implement Iterable. Iterable is a factory method for Iterator. Enumeration is analogous to Iterator, and only maintains state for a single enumeration.

So, be careful trying to wrap an Enumeration as an Iterable. If someone passes me an Iterable, I will assume that I can call iterator() on it repeatedly, creating as many Iterator instances as I want, and iterating independently on each. A wrapped Enumeration will not fulfill this contract; don't let your wrapped Enumeration escape from your own code. (As an aside, I noticed that Java 7's DirectoryStream violates expectations in just this way, and shouldn't be allowed to "escape" either.)

Enumeration is like an Iterator, not an Iterable. A Collection is Iterable. An Iterator is not.

You can't do this:

Vector<X> list = …
Iterator<X> i = list.iterator();
for (X x : i) {
    x.doStuff();
}

So it wouldn't make sense to do this:

Vector<X> list = …
Enumeration<X> i = list.enumeration();
for (X x : i) {
    x.doStuff();
}

There is no Enumerable equivalent to Iterable. It could be added without breaking anything to work in for loops, but what would be the point? If you are able to implement this new Enumerable interface, why not just implement Iterable instead?

AFAIK Enumeration is kinda "deprecated":

Iterator takes the place of Enumeration in the Java collections framework

I hope they'll change the Servlet API with JSR 315 to use Iterator instead of Enumeration.

If you would just like it to be syntactically a little cleaner, you can use:

while(e.hasMoreElements()) {
  doStuff(e.nextElement());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!