Saturday, 12 September 2015

ListIterator in Java

Though there is already an iterator provided for the list, which will iterate sequentially through all the elements in a list but it is uni-directional.

Iteration of a list

So if we are iterating this ArrayList we can only go from left to right. If we have any such requirement where we want to iterate the list in both directions we can use ListIterator. ListIterator provides both next() and previous() methods to iterate in both directions.

The interesting point about list iterator is that it has no current element. Its current cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions.

Iterating a list using list iterator

ListIterator methods summary

  1. add(E e) - Inserts the specified element into the list (optional operation).
  2. hasNext() - Returns true if this list iterator has more elements when traversing the list in the forward direction.
  3. hasPrevious() - Returns true if this list iterator has more elements when traversing the list in the reverse direction.
  4. next() - Returns the next element in the list and advances the cursor position.
  5. nextIndex() - Returns the index of the element that would be returned by a subsequent call to next().
  6. previous() - Returns the previous element in the list and moves the cursor position backwards.
  7. previousIndex() - Returns the index of the element that would be returned by a subsequent call to previous().
  8. remove() - Removes from the list the last element that was returned by next() or previous() (optional operation).
  9. set(E e) - Replaces the last element returned by next() or previous() with the specified element (optional operation).

Note that the remove() and set(object) methods are not defined in terms of the cursor position, they are defined to operate on the last element returned by a call to next() or previous().

public class ListIteratorDemo {
    public static void main(String[] args) {
        List<Integer> numberList = new ArrayList<Integer>();
        ListIterator<Integer> ltr = null;
        numberList.add(25);
        numberList.add(17);
        numberList.add(108);
        numberList.add(76);
        numberList.add(2);
        numberList.add(36);
        ltr = numberList.listIterator();
        //forward iteration
        System.out.println("Iterating list in forward direction");
        while(ltr.hasNext()){
            System.out.println(ltr.next());
        }
        // backward iteration 
        System.out.println("Iterating list in backward direction");
        while(ltr.hasPrevious()){
            System.out.println(ltr.previous());
        }
    }
}

Here we are first going forward using next() method. When the forward iteration is done cursor is after the last element so we can go backward using previous method() till the start of the list and that's what is done in the code.

Points to note

  • ListIterator provides an add(E e) method which is not there in Iterator. add(E e) inserts the specified element into the list (optional operation). The element is inserted immediately before the element that would be returned by next(), if any, and after the element that would be returned by previous(), if any.
  • ListItearator also provides set method. void set(E e) replaces the last element returned by next() or previous() with the specified element (optional operation). This call can be made only if neither remove() nor add(E) have been called after the last call to next or previous.
  • ListIterator is fail-fast and will throw a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add methods.

That's all for this topic ListIterator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList works internally in Java
  2. How to loop/iterate an arraylist in Java
  3. How to join lists in Java
  4. How to remove duplicate elements from an ArrayList in Java
  5. How to sort arraylist in Java
  6. How to sort arraylist of custom objects in Java
  7. Java Collections interview questions

You may also like -

No comments:

Post a Comment