Curriculum
In Java, ListIterator is an interface that extends the Iterator interface, and it provides bidirectional traversal and modification operations for a list. ListIterator is implemented by the List interface, so any list implementation in Java can create a ListIterator. Here is an example of how ListIterator is used in Java:
import java.util.ArrayList; import java.util.ListIterator; public class ListIteratorExample { public static void main(String[] args) { ArrayList<String> colors = new ArrayList<>(); colors.add("Red"); colors.add("Green"); colors.add("Blue"); ListIterator<String> iterator = colors.listIterator(); while (iterator.hasNext()) { String color = iterator.next(); System.out.println(color); } while (iterator.hasPrevious()) { String color = iterator.previous(); System.out.println(color); } } }
In this example, we have an ArrayList of colors, and we create a ListIterator using the listIterator()
method of the ArrayList class. We then use the hasNext()
and next()
methods to iterate through the list, and the hasPrevious()
and previous()
methods to iterate backwards through the list.
The ListIterator interface in Java has the following methods:
boolean hasNext()
: Returns true if there are more elements in the list.E next()
: Returns the next element in the list.boolean hasPrevious()
: Returns true if there are more elements in the list in the reverse order.E previous()
: Returns the previous element in the list.int nextIndex()
: Returns the index of the next element.int previousIndex()
: Returns the index of the previous element.void remove()
: Removes the last element returned by the iterator from the list.void set(E e)
: Replaces the last element returned by the iterator with the specified element.void add(E e)
: Inserts the specified element into the list.Note that the remove()
, set()
, and add()
methods modify the list, and they can only be called after a call to next()
, previous()
, nextIndex()
, or previousIndex()
. Also note that not all list implementations may support bidirectional iteration and modification, in which case an UnsupportedOperationException will be thrown.