Sunday 25 May 2014

LinkedList : remove : Retrieves and removes the head of the list

public E remove()
Retrieves and removes the head (first element) of this list.

import java.util.*;

class LinkedListRemove{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.print("Removed Element from myList is ");
  System.out.println(myList.remove());
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[10, 20, 30, 40]
Removed Element from myList is 10
Elements in myList are
[20, 30, 40]

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

class LinkedListRemoveNoSuch{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.print("Removed Element from myList is ");
  System.out.println(myList.remove());
 }
}

Output
Elements in myList are
[]
Removed Element from myList is Exception in thread "main" java.util.NoSuchElemen
tException
        at java.util.LinkedList.removeFirst(LinkedList.java:268)
        at java.util.LinkedList.remove(LinkedList.java:683)
        at LinkedListRemoveNoSuch.main(LinkedListRemoveNoSuch.java:12)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment