开发者

Use of Java Enumerations/Iterators

开发者 https://www.devze.com 2023-02-25 05:23 出处:网络
I was just roaming through the API and it came to my attention that, Enumerations and Iterators aren\'t very useful interfaces.

I was just roaming through the API and it came to my attention that, Enumerations and Iterators aren't very useful interfaces.

Specifically I mean, instead of saying (for V开发者_JAVA百科ector v):

for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
   System.out.println(e.nextElement());

We can easily say:

for (int i = 0; i < v.size(); i++)
   System.out.println(v.elementAt(i));

What I wanted to know exactly is:

Are there any performance bonuses for using Enumerations/Iterators?

Has it provided you the ability to achieve something that cannot be achieved by the latter for loop?


Not everything that has an Iterator is a random access List. A Set, for example, doesn't allow indexed access. A LinkedList allows it, but looping by index would have terrible performance.

Other things that aren't a Collection at all have Iterators or can be represented as an Iterator as well. For example, one can represent an infinite sequence with an Iterator.

Having a simple, common interface that's used for iterating through things allows for methods that can operate on as wide a variety of objects as possible.

As an aside, both Vector and Enumeration are outdated and have basically been replaced in modern Java by ArrayList and Iterator respectively.


I don't think iterators and enumerations are about performance; they're about better abstraction.

You don't need to know anything about the underlying data structure if you have an iterator. That's why I think that interface is perfectly acceptable. I don't agree with your statement that Iterator isn't a useful interface. What methods would you add?


Aside from the fact that Enumerators and Iterators are better at expressing what you are trying to do when you are trying to walk the values in a collection, and abstract away the details of the particular collection type as duffymo mentioned, the Iterator interface allows you to use the much more elegant for syntax such as:

List<String> list = new ArrayList<String>();
for(String entry : list)
{
    System.out.println(list);
}


It's safe to modify the list while iterating using the Iterator.hasNext() method. If you simply check whether the index is less than the original size, you could run into problems...


iterator is about decouple and encapsulation. You don't need to care data structure difference, iterator has unique API to expose. As a result, client code doesn't need too much refactory even if collection changed. Before jdk 1.5, we use interface to manage some static final fields. You can compare them by writing some sample codes - (enum supports switch, e.g.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号