Sunday, 11 May 2014

LinkedList : getLast : get the Last Element in the List

public E getLast()
Returns the last element in this list.

import java.util.*;

class LinkedListGetLast{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<Integer> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("Elements in myList are " + myList);
  System.out.print("\nLast Element in the List is ");
  System.out.println(myList.getLast());
 }
}

Output
Elements in myList are [10, 20, 30, 40]

Last Element in the List is 40

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

class LinkedListGetLastNoSuch{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<Integer> ();
  
  System.out.println("Elements in myList are " + myList);
  System.out.print("\nLast Element in the List is ");
  System.out.println(myList.getLast());
 }
}

Output
Elements in myList are []

Last Element in the List is Exception in thread "main" java.util.NoSuchElementException
        at java.util.LinkedList.getLast(LinkedList.java:255)
        at LinkedListGetLastNoSuch.main(LinkedListGetLastNoSuch.java:10)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment