Sunday, 11 May 2014

LinkedList : getFirst : Get the First Element of the List

public E getFirst()
Returns the first element in this list.

import java.util.*;

class LinkedListGetFirst{
  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("\nFirst Element in the List is ");
  System.out.println(myList.getFirst());
  }
}

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

First Element in the List is 10

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

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

Output
Elements in myList are []

First Element in the List is Exception in thread "main" java.util.NoSuchElementException
        at java.util.LinkedList.getFirst(LinkedList.java:242)
        at LinkedListGetFirstNoSuch.main(LinkedListGetFirstNoSuch.java:10)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment