What are the benefits of the Iterator interface in Java?

24,594

Solution 1

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.

Solution 2

You ask: "Why are the methods hasNext(), next() and remove() not directly coded to the data structure implementation itself?".

The Java Collections framework chooses to define the Iterator interface as externalized to the collection itself. Normally, since every Java collection implements the Iterable interface, a Java program will call iterator to create its own iterator so that it can be used in a loop. As others have pointed out, Java 5 allows us to direct usage of the iterator, with a for-each loop.

Externalizing the iterator to its collection allows the client to control how one iterates through a collection. One use case that I can think of where this is useful is when one has an an unbounded collection such as all the web pages on the Internet to index.

In the classic GoF book, the contrast between internal and external iterators is spelled out quite clearly.

A fundamental issue is deciding which party conrols the iteration, the iterator or the client that uses the iterator. When the client controls the iteration, the iterator is called an external iterator, and when the iterator controls it, the iterator is an internal iterator. Clients that use an external iterator must advance the traversal and request the next element explicitly from the iterator. In contrast, the client hands an internal iterator an operation to perform, and the iterator applies that operation to every element ....

External iterators are more flexible than internal iterators. It's easy to compare two collections for equality with an external iterator, for example, but it's practically impossible with internal iterators ... But on the other hand, internal iterators are easier to use, because they define the iteration logic for you.

For an example of how internal iterators work, see Ruby's Enumerable API, which has internal iteration methods such as each. In Ruby, the idea is to pass a block of code (i.e. a closure) to an internal iterator so that a collection can take care of its own iteration.

Solution 3

it is important to keep the collection apart from the pointer. the iterator points at a specific place in a collection, and thus is not an integral part of the collection. this way, for an instance, you can use several iterators over the same collection.

the down-side of this seperation is that the iterator is not aware to changes made to the collection it iterates on. so you cannot change the collection's structure and expect the iterator to continue it's work without "complaints".

Solution 4

Multiple instances of an interator can be used concurrently. Approach them as local cursors for the underlying data.

BTW: favoring interfaces over concrete implementations looses coupling

Look for the iterator design pattern, and here: http://en.wikipedia.org/wiki/Iterator

Solution 5

Using the Iterator interface allows any class that implements its methods to act as iterators. The notion of an interface in Java is to have, in a way, a contractual obligation to provide certain functionalities in a class that implements the interface, to act in a way that is required by the interface. Since the contractual obligations must be met in order to be a valid class, other classes which see the class implements the interface and thus reassured to know that the class will have those certain functionalities.

In this example, rather than implement the methods (hasNext(), next(), remove()) in the LinkedList class itself, the LinkedList class will declare that it implements the Iterator interface, so others know that the LinkedList can be used as an iterator. In turn, the LinkedList class will implement the methods from the Iterator interface (such as hasNext()), so it can function like an iterator.

In other words, implementing an interface is a object-oriented programming notion to let others know that a certain class has what it takes to be what it claims to be.

This notion is enforced by having methods that must be implemented by a class that implements the interface. This makes sure that other classes that want to use the class that implements the Iterator interface that it will indeed have methods that Iterators should have, such as hasNext().

Also, it should be noted that since Java does not have multiple inheritance, the use of interface can be used to emulate that feature. By implementing multiple interfaces, one can have a class that is a subclass to inherit some features, yet also "inherit" the features of another by implementing an interface. One example would be, if I wanted to have a subclass of the LinkedList class called ReversibleLinkedList which could iterate in reverse order, I may create an interface called ReverseIterator and enforce that it provide a previous() method. Since the LinkedList already implements Iterator, the new reversible list would have implemented both the Iterator and ReverseIterator interfaces.

You can read more about interfaces from What is an Interface? from The Java Tutorial from Sun.

Share:
24,594
user17182
Author by

user17182

Updated on October 21, 2020

Comments

  • user17182
    user17182 over 3 years

    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 through the items in a data structure such as a list. Why is this interface used? Why are the methods hasNext(), next() and remove() not directly coded to the data structure implementation itself?

    From the Java website: link text

    public interface Iterator<E>

    An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:

    • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
    • Method names have been improved.
    This interface is a member of the Java Collections Framework.

    I tried googling around and can't seem to find a definite answer. Can someone shed some light on why Sun chose to use them? Is it because of better design? Increased security? Good OO practice?

    Any help will be greatly appreciated. Thanks.