ListIterator code example

Example 1: ArrayList listIterator() method in java

example on listIterator() method IndexOutOfBoundsException
import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListListIteratorMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("plum");
      al.add("apple");
      al.add("orange");
      al.add("mango");
      al.add("pineapple");
      System.out.println(al);
      ListIterator<String> iterate = al.listIterator(5);
      System.out.println(iterate.hasNext());
      iterate = al.listIterator(6);
   }
}

Example 2: ArrayList listIterator() method in java

import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListListIteratorMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("plum");
      al.add("apple");
      al.add("orange");
      al.add("mango");
      al.add("pineapple");
      System.out.println(al);
      ListIterator<String> iterate = al.listIterator(1);
      while(iterate.hasNext())
      {
         String str = iterate.next();
         System.out.println(str);
      }
   }
}

Example 3: 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);
        }
    }

}

Example 4: listIterator

import java.util.*;

public class ListIteratorDemo 
{
  public static void main(String[] args) 
  {
	List<String> names = new LinkedList<>();
	names.add("Rams");
	names.add("Posa");
	names.add("Chinni");
		
	// Getting ListIterator
	ListIterator<String> namesIterator = names.listIterator();
	
	// Traversing elements
	while(namesIterator.hasNext()){
	   System.out.println(namesIterator.next());			
	}	

	// Enhanced for loop creates Internal Iterator here.
	for(String name: names){
	   System.out.println(name);			
	}	
  }
}

Tags:

Java Example