Java ListIterator set method example :
In this example, we will learn how to use ListIterator in Java . ListIterator is an interface that extends Iterator interface. Using it, we can iterate a list in either direction. During the iteration, we can get the current position of the iterator and the value of the current element.
Check our previous example on ListIterator
set(E e) method :
next() method returns the next element of the list and move the current cursor position of the ListIterator. Similarly, previous() returns the previous element in the list and moves the cursor backward. set(E e) replaces the last element returned by next or previous with element e.
Let’s take a look into the example :
Java program :
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
ArrayList days = new ArrayList<>();
days.add("Sun");
days.add("Mon");
days.add("Tue");
days.add("Thu");
days.add("Fri");
days.add("Sat");
ListIterator iterator = days.listIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
iterator.set("None");
System.out.println("After set : ");
for (String item : days) {
System.out.println(item);
}
}
}
Output :
Sun
Mon
Tue
Thu
Fri
Sat
After set :
Sun
Mon
Tue
Thu
Fri
None