LinkedList removeFirst() method with example in java
The removeFirst() method of LinkedList retrieves and removes the first element in this list. It throws a NoSuchElementException exception if this list is empty.
Syntax
Object removeFirst()
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 LinkedListRemoveFirstExample { public static void main(String[] args) { LinkedListoddNumbers = new LinkedList(); oddNumbers.add(5); oddNumbers.add(7); oddNumbers.add(9); oddNumbers.add(11); System.out.println("Linked List elements: " + oddNumbers); oddNumbers.removeFirst(); System.out.println("Linked List after removing first element: " + oddNumbers); } }
Output
Linked List elements: [5, 7, 9, 11] Linked List after removing first element: [7, 9, 11]
Program 2
import java.util.LinkedList; public class LinkedListRemoveFirstExample { public static void main(String[] args) { LinkedListoddNumbers = 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.removeFirst();// throws NoSuchElementException as linked-list is null } }
Output
Exception in thread "main" Linked List elements: [5, 7, 9, 11] Linked List elements after clear() call: [] java.util.NoSuchElementException at java.util.LinkedList.removeFirst(LinkedList.java:270) at LinkedListRemoveFirstExample.main(LinkedListRemoveFirstExample.java:18)
0 Comments