What are the benefits of the Iterator interface in Java?

后端 未结 16 1924
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 14:35

I just learned about how the Java Collections Framework implements data structures in linked lists. From what I understand, Iterators are a way of traversing th

相关标签:
16条回答
  • 2020-12-04 15:17

    Ultimately, because Iterator captures a control abstraction that is applicable to a large number of data structures. If you're up on your category theory fu, you can have your mind blown by this paper: The Essence of the Iterator Pattern.

    0 讨论(0)
  • 2020-12-04 15:18

    Iterator is useful when you are dealing with Collections in Java.

    Use For-Each loop(Java1.5) for iterating over a collection or array or list.

    0 讨论(0)
  • 2020-12-04 15:21

    Iterators can be used against any sort of collection. They allow you to define an algorithm against a collection of items regardless of the underlying implementation. This means you can process a List, Set, String, File, Array, etc.

    Ten years from now you can change your List implementation to a better implementation and the algorithm will still run seamlessly against it.

    0 讨论(0)
  • 2020-12-04 15:22

    Why is this interface used?

    Because it supports the basic operations that would allow a client programmer to iterate over any kind of collection (note: not necessarily a Collection in the Object sense).

    Why are the methods... not directly coded to the data structure implementation itself?

    They are, they're just marked Private so you can't reach into them and muck with them. More specifically:

    • You can implement or subclass an Iterator such that it does something the standard ones don't do, without having to alter the actual object it iterates over.
    • Objects that can be traversed over don't need to have their interfaces cluttered up with traversal methods, in particular any highly specialized methods.
    • You can hand out Iterators to however many clients you wish, and each client may traverse in their own time, at their own speed.
    • Java Iterators from the java.util package in particular will throw an exception if the storage that backs them is modified while you still have an Iterator out. This exception lets you know that the Iterator may now be returning invalid objects.

    For simple programs, none of this probably seems worthwhile. The kind of complexity that makes them useful will come up on you quickly, though.

    0 讨论(0)
提交回复
热议问题