Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – ListIterator

Declaration

interface ListIterator<E>

ListIterator extends Iterator interface.

Iterator traverses in single direction that is in forward direction, whereas ListIterator traverses in forward & backward direction of a list.

In addition to obtaining & removing elements from collection like Iterator it also modifies the elements.

List of ListIterator Methods (CLICK HERE)

Example

 import java.util.ArrayList;
 import java.util.ListIterator;

 public class ListIteratorDemo 
 {
     public static void main(String args[])
     {
         ArrayList<Integer> al = new ArrayList<Integer>();
         int num = 10;
         for(int i=1;i<=6;i++)
         {
        	al.add(num);
        	num = num+10;
         }
         System.out.println("ArrayList :: "+al);
		
         ListIterator<Integer> itr = al.listIterator();
         while(itr.hasNext())
         {
             Integer i = itr.next();
             if(i==20)
             {
                 itr.add(30);
             }
             if(i==60)
             {
                 itr.remove();
             }
             if(i==50)
             {
                 itr.set(80);
             }
         }
         System.out.println("After Modifications :: "+al);
     }
 }

Output

ArrayList :: [10, 20, 30, 40, 50, 60]
After Modifications :: [10, 20, 30, 30, 40, 80]

 

Leave a reply