ListIterator in Java

ListIterator in Java

Java  has  an  interface ListIterator. It is an enhanced version of Iterator interface. The purpose of ListIterator is to iterate data in collections. If  we use Iterator , then iteration is allowed only in forward direction. But if we use ListIterator iteration in both directions is possible.That is the difference between Iterator and ListIterator.

Methods in ListIterator.

Now , let us see the methods in ListIterator. There are 9 methods in ListIterator.

1)E next()

    2)boolean hasNext()

3)void remove()

4)boolean hasPrevious()

5)E previous()

6)int nextIndex()

7) int previousIndex()

8)void set(E e)

9) void add(E e)

The first  3 methods are there in Iterator .Others are added in ListIterator.Now let us see an example.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IteratorSample {
List list = null;
public IteratorSample() {
list = new ArrayList();
}
public void addItems() {
list.add("cat");
list.add("dog");
list.add("cow");
}
public void displayItems() {
System.out.println("Forward");
ListIterator iterator = list.listIterator();
System.out.println("Iterating the list");
while (iterator.hasNext()) {
System.out.println(iterator.next().toString());
}
System.out.println("Reverse");
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
}
public static void main(String[] args) {
IteratorSample sample = new IteratorSample();
sample.addItems();
sample.displayItems();
}
}

The addeItems() method adds few Strings into an ArrayList.The displayItems() method creates a ListIterator object and by using that object iterating the ArrayList in forward and reverse directions.

Output

Forward

Iterating the list

cat

dog

cow

Reverse

cow

dog

cat

So if we need to iterate collections in both directions ListIterator is suitable.

See Related Topics:

Collections in java

Threading in Java