set method in listiterator in java 1

set method in listiterator in java

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);
        }
    }

}

Here is what the above code is Doing:
1. We create an ArrayList of days.
2. We add some days to the ArrayList.
3. We create a ListIterator object and assign it to the iterator variable.
4. We use the hasNext() method to check if there are more elements in the ArrayList.
5. We use the next() method to get the next element in the ArrayList.
6. We use the set() method to set the current element to “None”.
7. We use the for-each loop to print the elements of the ArrayList.

Similar Posts