Thursday 8 May 2014

Vector : listIterator(int index) : Get iterator from index

public synchronized ListIterator<E> listIterator(int index)
Returns a list iterator over the elements in this list, starting at the specified position in the list.

import java.util.*;

class VectorListIterator{
 public static void main(String args[]){
  Vector<Integer> myVector;
  ListIterator<Integer> myIter;
  
  myVector = new Vector<> ();
  
  /*Add Elements to myVector*/
  myVector.add(10);
  myVector.add(11);
  myVector.add(12);
  myVector.add(13);
  myVector.add(14);

  myIter = myVector.listIterator(2);
  
  System.out.println("Elements in Forward order");
  while(myIter.hasNext()){
   System.out.print(myIter.next() +" ");
  }
  
  System.out.println("\nElements in Reverse order");
  while(myIter.hasPrevious()){
   System.out.print(myIter.previous() +" ");
  }
 }
}

Output
Elements in Forward order
12 13 14
Elements in Reverse order
14 13 12 11 10

1. Throws IndexOutOfBoundsException if index is out of range
import java.util.*;

class VectorListIteratorIndexOut{
 public static void main(String args[]){
  Vector<Integer> myVector;
  ListIterator<Integer> myIter;
  
  myVector = new Vector<> ();
  
  /*Add Elements to myVector*/
  myVector.add(10);
  myVector.add(11);
  myVector.add(12);
  myVector.add(13);
  myVector.add(14);

  myIter = myVector.listIterator(-1);
 }
}

Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: -1
        at java.util.Vector.listIterator(Vector.java:1090)
        at VectorListIteratorIndexOut.main(VectorListIteratorIndexOut.java:17)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment