LinkedList removeLast() method with example in java
The removeLast() method of LinkedList retrieves and removes the last element in this list. It throws a NoSuchElementException if this list is empty.
Syntax
Object removeLast() |
Parameters
It doesn't take any parameter
Return Value
the removed element in this list
Exception
It throws NoSuchElementException exception if this list is empty.
Program 1
import java.util.LinkedList; public class LinkedListRemoveLastExample { public static void main(String[] args) { LinkedList<integer> oddNumbers = new LinkedList(); oddNumbers.add( 5 ); oddNumbers.add( 7 ); oddNumbers.add( 9 ); oddNumbers.add( 11 ); System.out.println( "Linked List elements: " + oddNumbers); oddNumbers.removeLast(); System.out.println( "Linked List after removing last element: " + oddNumbers); } } </integer> |
Output
Linked List elements: [5, 7, 9, 11] Linked List after removing last element: [5, 7, 9]
Program 2
import java.util.LinkedList; public class LinkedListRemoveLastExample { public static void main(String[] args) { LinkedList<integer> oddNumbers = new LinkedList(); oddNumbers.add( 5 ); oddNumbers.add( 7 ); oddNumbers.add( 9 ); oddNumbers.add( 11 ); System.out.println( "Linked List elements: " + oddNumbers); oddNumbers.clear(); System.out.println( "Linked List elements after clear() call: " + oddNumbers); oddNumbers.removeLast(); // throws NoSuchElementException as linked-list is null } } </integer> |
Output
Linked List elements: [5, 7, 9, 11] Linked List elements after clear() call: [] Exception in thread "main" java.util.NoSuchElementException at java.util.LinkedList.removeLast(LinkedList.java:283) at LinkedListRemoveLastExample.main(LinkedListRemoveLastExample.java:18)
0 Comments