Thursday, 8 May 2014

Vector : lastElement : Get the last element of the vector

public synchronized E lastElement()
Returns the last component of the vector.

import java.util.*;

class VectorLastElement{
 public static void main(String args[]){
  Vector<Integer> myVector;
  myVector = new Vector<> ();
  
  /*Add Elements to myVector*/
  myVector.add(10);
  myVector.add(11);
  myVector.add(12);
  myVector.add(10);
  myVector.add(12);
  
  System.out.print("Last Element Of the Vector is "); 
  System.out.println(myVector.lastElement());
 }
}

Output
Last Element Of the Vector is 12

1. Throws NoSuchElementException if this vector is empty
import java.util.*;

class VectorLastElementNoSuch{
 public static void main(String args[]){
  Vector<Integer> myVector;
  myVector = new Vector<> ();
  
  System.out.print("Last Element Of the Vector is "); 
  System.out.println(myVector.lastElement());
 }
}

Output
Last Element Of the Vector is Exception in thread "main" java.util.NoSuchElement
Exception
        at java.util.Vector.lastElement(Vector.java:499)
        at VectorLastElementNoSuch.main(VectorLastElementNoSuch.java:9)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment