Java’s Iterator, ListIterator and Iterable Explained

Recall Collection: A container for Objects in Java. Example: ArrayList<E>, Vector<E>, Set<E>, etc.

 An iterator is an Object, which enables a Collection<E> to be traversed. It allows developers to retrieve data elements in a Collection without any knowledge of the underlying data structure, whether it is an ArrayList, LinkedList, Set or some other kind.

The concept behind iterator is very simple: An Iterator is always returned by a Collection and has methods such as next() which returns the next element in the Collection, hasNext() which returns a boolean value indicating if there are more elements in the Collection or not, etc.

Iterators promote “loose coupling” between Collection classes and the classes using these Collections. For example, a class containing some kind of an algorithm (e.g. Search) is only concerned with traversing the list without knowing the exact list structure or any low level details.

Interface Iterator<E>:

All Iterator objects must implement this interface and are bound by its protocols. The interface is very simple and only has three methods:

-       next() : Returns the next element in the Collection. To get all elements in a Collection, call this method repeatedly. When the end is reached and there are no more elements present, this method throws NoSuchElementException.

-       hasNext() : returns true if the Collection has more elements. false otherwise.

-       remove() : removes the last returned element from the Collection.

A java.util.Iterator can only move in one direction: forward. Once the iterator has reached the end of the list, it cannot be reset to the starting position again. In this case, a new Iterator should be obtained.

Interface ListIterator<E>:

This is a specialized Iterator for Collections implementing the List<E> interface. In other words, it is an iterator for Lists. It gives several advantages over Iterator namely:

  1. It allows traversing in both directions: forward & backward
  2. It allows for obtaining the Iterator position in the Collection, i.e. its index.
  3. It allows for adding or removing elements of the underlying List. [set(..) works as well].

You must be wondering at this point, why a new kind of Iterator for Lists? Why can’t we use the plain old Iterator. But if you really think about it, you’ll see why: Let us say you have two Collections: a Set<E> and a List<E>. You get Iterators from both Collections to traverse the list. However, you feel that the Iterator returned by List can do more: It can return the current index, allow you to add an element to the list, etc. That’s where ListIterator’s come in. The Iterator returned by Set<E> doesn’t have to do any of this: an element as no position(index) in the Set<E> Collection etc.

Interface Iterable<E>:

Before I wrap this us, I want to discuss the Iterable<E> interface. It is a very simple Interface which defines only one method called iterator() which returns an Iterator<E>.

The sole purpose of this interface is to allow Objects implementing it to be used in for-each loop. A for-each loop in Java looks like the following:

for (String element: (Iterable)collectionImplemetingIterable) { //do something with element}

For example: ArrayList() implements Iterable. This allows you to pass an ArrayList() object to a for-each loop and traverse through it.

e.g.

ArrayList as = new ArrayList();
as.add(“hippo”);
as.add(“chicken”);
as.add(“duck”);

// traverse the List using for-each
for (String element : as)
	System.out.println(element);

Summary:

An iterator allows traversing a Collection. An Iterator could be obtained for virtually any kind of Collection, for example:

ArrayList as = …;
HashSet hs = ….;

Now let us get Iterators for the two Collections defined above:

Iterator asIterator = as.iterator();
Iterator hsIterator = hs.iterator();

To iterate over the two collections:

</pre>
while(asIterator.hasNext) //Iterate over ArrayList()
{
    System.out.println(asIterator.next());
}

while(hsIterator.hasNext) //Iterate over HashSet()
{
    System.out.println(hsIterator.next());
}

Notes:

  • Java iterators are very much like Relational Database Cursors.
  • Prior to Iterators, which were introduced in jdk1.2, programmers used enumeration to traverse Collections.
About these ads
About

I'm Umer Mansoor , the author of this blog.

Tagged with: , , ,
Posted in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: