Tuesday 6 May 2014

Vector : elementAt : Get Element at index

public synchronized E elementAt(int index)
Returns the element at the specified index.

import java.util.*;

class VectorElementAt{
 public static void main(String args[]){
  Vector<Integer> myVector;
  
  myVector = new Vector<> ();
  
  /* Add Elements to myVector */
  for(int i=1; i<6; i++)
   myVector.add(i); 
  
  for(int i=0; i<5; i++){
   System.out.println("Element At index " + i +" is");
   System.out.println(myVector.elementAt(i));
  }
 }
}

Output
Element At index 0 is
1
Element At index 1 is
2
Element At index 2 is
3
Element At index 3 is
4
Element At index 4 is
5

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

class VectorElementAtIndexOut{
 public static void main(String args[]){
  Vector<Integer> myVector;
  
  myVector = new Vector<> ();
  
  /* Add Elements to myVector */
  for(int i=1; i<6; i++)
   myVector.add(i); 
  
  System.out.println("Element At index " + 100 +" is");
  System.out.println(myVector.elementAt(100));
 }
}

Output
Element At index 100 is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100 >= 5
        at java.util.Vector.elementAt(Vector.java:470)
        at VectorElementAtIndexOut.main(VectorElementAtIndexOut.java:14)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment