Tuesday 6 May 2014

Vector : firstElement : get the First Element

public synchronized E firstElement()
Returns the first Element in this vector.

import java.util.*;

class VectorFirstElement{
 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("Elements in myVector are");
  System.out.println(myVector);
  
  System.out.print("First Element in myVector is ");
  System.out.println(myVector.firstElement());
 }
}

Output
Elements in myVector are
[1, 2, 3, 4, 5]
First Element in myVector is 1

1. Throws NoSuchElementException if this vector has no components
import java.util.*;

class VectorFirstElementNullpointer{
 public static void main(String args[]){
  Vector<Integer> myVector; 
  myVector = new Vector<> ();
 
  System.out.println(myVector.firstElement());
 }
}

Output
Exception in thread "main" java.util.NoSuchElementException
        at java.util.Vector.firstElement(Vector.java:485)
        at VectorFirstElementNullpointer.main(VectorFirstElementNullpointer.java:8)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment