Sunday 25 May 2014

LinkedList : removeLast : Removes and returns the last element from this list.

public E removeLast()
Removes and returns the last element from this list.

import java.util.*;

class LinkedListRemoveLast{
 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.println("\nCalling removeLast");
  myList.removeLast();
  
  System.out.println("\nElements in myList are");
  System.out.println(myList);
 }
}

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

Calling removeLast

Elements in myList are
[10, 20, 30]

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

class LinkedListRemoveLastNoSuch{
 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.println("\nCalling removeLast");
  myList.removeLast();
  
  System.out.println("\nElements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[]

Calling removeLast
Exception in thread "main" java.util.NoSuchElementException
        at java.util.LinkedList.removeLast(LinkedList.java:281)
        at LinkedListRemoveLastNoSuch.main(LinkedListRemoveLastNoSuch.java:12)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment