ListIterator interface in collection

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list. A ListIterator has no current element; its 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().

Accessing a Collection
To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements of any collection.

Using Iterator interface

Using ListIterator interface

Using for-each loop

Accessing elements using Iterator:
Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator.The Methods Declared by Iterator:

SN

Methods with Description

1

boolean hasNext( )
Returns true if there are more elements. Otherwise, returns false.

2

Object next( )
Returns the next element. Throws NoSuchElementException if there is not a next element.

3

void remove( )
Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).

Accessing element using ListIterator:ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implement the List Interface.

Object next( )
Returns the next element. A NoSuchElementException is thrown if there is not a next element.

5

int nextIndex( )
Returns the index of the next element. If there is not a next element, returns the size of the list.

6

Object previous( )
Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.

7

int previousIndex( )
Returns the index of the previous element. If there is not a previous element, returns -1.

8

void remove( )
Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.

9

void set(Object obj)
Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

Using for-each loopfor-each version of for loop can also be used for traversing each element of a collection. But this can only be used if we don’t want to modify the contents of a collection and we don’t want any reverse access. for-each loop can cycle through any collection of object that implements Iterable interface.