ListIterator in Java

 

ListIterator in Java

ListIterator is an interface in Java that works specifically with the List interface and is inherited from the Iterator interface. It is used to iterate over Lists such as ArrayList, Vector, and LinkedList.

In addition to the methods inherited from the Iterator interface such as next(), hasNext(), and remove(), ListIterator also provides methods like hasPrevious(), previous(), add(), set(), nextIndex(), and previousIndex().

We can use ListIterator to traverse a List in both forward and backward directions. The listIterator() method gives us an iterator pointing to the first element, while the listIterator(int index) method gives us an iterator pointing to a specific element. We can pass the size of the list as a parameter to get an iterator pointing to the last element.

The set() method in ListIterator is used to replace the element returned by either next() or previous() with the specified element. The add() method is used to add an item while iterating through the List.

Here is an example of forward traversal using ListIterator:

scss
List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); ListIterator<Integer> it = list.listIterator(); while (it.hasNext()) { System.out.println(it.next()); }

Output:

10 20 30

Here is an example of backward traversal using ListIterator:

scss
List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); ListIterator<Integer> it = list.listIterator(list.size()); while (it.hasPrevious()) { System.out.println(it.previous()); }

Output:

30 20 10

Finally, here is an example of using the set() method to replace each element with double of its value:

scss
List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); ListIterator<Integer> it = list.listIterator(list.size()); while (it.hasPrevious()) { int x = it.previous(); it.set(x * 2); } System.out.println(list);

Output:

csharp
[20, 40, 60]

And here is an example of using the add() method to insert an element 5 before each element of the List:

scss
List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); ListIterator<Integer> it = list.listIterator(); while (it.hasNext()) { it.add(5); it.next(); } System.out.println(list);

Output:

csharp
[5, 10, 5, 20, 5, 30]
Previous Post Next Post