LinkedList removeFirst() Method in Java
In Java, the removeFirst() method of the LinkedList class is used to remove and return the first element of the list.
Example 1: Here, we use the removeFirst() method to remove the first element (head) of the LinkedList of Integers.
// Java Program to demonstrate the
// use of removeFirst() in LinkedList
import java.util.LinkedList;
class Geeks {
public static void main(String[] args) {
// Creating an empty list
LinkedList<Integer> l = new LinkedList<>();
// use add() to add
// elements in the list
l.add(100);
l.add(200);
l.add(300);
l.add(400);
System.out.println("" + l);
// Removing the First element
// form the list
System.out.println("Removed First element: " + l.removeFirst());
System.out.println("" + l);
}
}
Output
[100, 200, 300, 400] Removed First element: 100 [200, 300, 400]
Syntax of LinkedList remove() Method
public E removeFirst()
- Return Type: The method returns the first element (head) that is removed from the list.
- Exception: If the list is empty, calling removeFirst() will throw a NoSuchElementException.
Example 2: Here, the removeFirst() is going to throw an NoSuchElementException
if the list is empty.
// Handling NoSuchElementException with removeFirst()
import java.util.LinkedList;
class Geeks {
public static void main(String[] args) {
// Here we are trying to remove
// first element from an empty list
try {
LinkedList<String> l = new LinkedList<>();
l.removeFirst();
}
catch (Exception e) {
System.out.println("Exception caught: " + e);
}
}
}
Output
Exception caught: java.util.NoSuchElementException