Java ListIterator
In Java, a ListIterator
is an interface that provides a way to traverse a List
in both directions, and also to modify the list during iteration. It extends the Iterator
interface and provides additional methods for bidirectional iteration, insertion, and replacement of elements.
The ListIterator
interface has the following methods:
boolean hasNext()
: Returns true if there are more elements in the list in the forward direction.E next()
: Returns the next element in the list in the forward direction.boolean hasPrevious()
: Returns true if there are more elements in the list in the backward direction.E previous()
: Returns the previous element in the list in the backward direction.int nextIndex()
: Returns the index of the next element in the list in the forward direction.int previousIndex()
: Returns the index of the previous element in the list in the backward direction.void remove()
: Removes the last element returned by the iterator from the underlying 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 immediately before the next element that would be returned bynext()
.
Here's an example of how to use a ListIterator
in Java:
import java.util.ArrayList; import java.util.ListIterator; public class ListIteratorExample { public static void main(String[] args) { // Create a new ArrayList ArrayList<String> list = new ArrayList<>(); // Add some elements to the list list.add("apple"); list.add("banana"); list.add("cherry"); // Create a ListIterator for the list ListIterator<String> iterator = list.listIterator(); // Iterate over the list in the forward direction while (iterator.hasNext()) { String element = iterator.next(); System.out.println(element); } // Iterate over the list in the backward direction while (iterator.hasPrevious()) { String element = iterator.previous(); System.out.println(element); } } }Sruoce:www.theitroad.com
Output:
apple banana cherry cherry banana apple
In the example above, we have created an ArrayList
of strings, and added three elements to it. We have then created a ListIterator
for the list using the listIterator()
method of the ArrayList
class. We have used a while
loop to iterate over the list in the forward direction using the hasNext()
and next()
methods of the ListIterator
. We have then used another while
loop to iterate over the list in the backward direction using the hasPrevious()
and previous()
methods of the ListIterator
. We have printed each element to the console using System.out.println()
.
Note that the ListIterator
interface can also be used to insert and replace elements in the list using the add()
and set()
methods. These methods modify the list during iteration, so it is important to use them carefully to avoid unexpected behavior.