Skip to Content

Get Previous and next index using Java ListIterator Example

  1. /*
  2.   Get Previous and next index using Java ListIterator Example
  3.   This Java Example shows how to get previous and next index while traversing through
  4.   elements of ArrayList using Java ListIterator.
  5. */
  6.  
  7. import java.util.ListIterator;
  8. import java.util.ArrayList;
  9.  
  10. public class GetPreviousAndNextIndexListIteratorExample {
  11.  
  12.   public static void main(String[] args) {
  13.     //create an object of ArrayList
  14.     ArrayList aList = new ArrayList();
  15.    
  16.     //Add elements to ArrayList object
  17.     aList.add("1");
  18.     aList.add("2");
  19.     aList.add("3");
  20.     aList.add("4");
  21.     aList.add("5");
  22.    
  23.     //Get an object of ListIterator using listIterator() method
  24.     ListIterator listIterator = aList.listIterator();
  25.  
  26.     /*
  27.       Use nextIndex and previousIndex methods of ListIterator to get next and
  28.       previous index from the current position in the list.
  29.     */
  30.    
  31.     System.out.println("Previous Index is : " + listIterator.previousIndex());  
  32.     System.out.println("Next Index is : " + listIterator.nextIndex());
  33.    
  34.     //advance current position by one using next method
  35.     listIterator.next();
  36.    
  37.     System.out.println("After increasing current position by one element : ");
  38.     System.out.println("Previous Index is : " + listIterator.previousIndex());  
  39.     System.out.println("Next Index is : " + listIterator.nextIndex());
  40.    
  41.    
  42.   }
  43. }
  44.  
  45. /*
  46. Previous Index is : -1
  47. Next Index is : 0
  48. After increasing current position by one element :
  49. Previous Index is : 0
  50. Next Index is : 1
  51. */