Tuesday 6 May 2014

Vector : get : get the Element at Specific index

public synchronized E get(int index)
Returns the element at the specified position in this Vector.

import java.util.*;

class VectorGet{
 public static void main(String args[]){
  Vector<Integer> myVector;
  
  myVector = new Vector<> ();
  
  /* Add Elements to myVector */
  myVector.add(12);
  myVector.add(2);
  myVector.add(88);
  myVector.add(-98);
   
  System.out.println("Elements in myVector are");
  System.out.println(myVector);
  
  System.out.print("Element at 2nd position is ");
  System.out.println(myVector.get(2));
 }
}

Output
Elements in myVector are
[12, 2, 88, -98]
Element at 2nd position is 88

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

class VectorGetIndexOut{
 public static void main(String args[]){
  Vector<Integer> myVector;
  
  myVector = new Vector<> ();
  
  /* Add Elements to myVector */
  myVector.add(12);
  myVector.add(2);
  myVector.add(88);
  myVector.add(-98);
   
  System.out.println("Elements in myVector are");
  System.out.println(myVector);
  
  System.out.print("Element at -1 th Position ");
  System.out.println(myVector.get(-1));
 }
}

Output
Elements in myVector are
[12, 2, 88, -98]
Element at -1 th Position Exception in thread "main" java.lang.ArrayIndexOutOfBo
undsException: -1
        at java.util.Vector.elementData(Vector.java:730)
        at java.util.Vector.get(Vector.java:746)
        at VectorGetIndexOut.main(VectorGetIndexOut.java:19)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment