removeFirst
method of the LinkedList
class?The removeFirst
method can be used to remove the first element of the linked list.
A linked list is a collection of linear data elements. Each element, or node, contains data and reference parts.
The elements are not indexed so random access is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedList
is aimplementation of the List and Deque interfaces. The doubly-linked list A kind of linked list. Each node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. LinkedList
class is present in thejava.util
package.
public E removeFirst();
This method doesn’t take any arguments. It removes and returns the first element of the list. If the list is empty then the NoSuchElementException
exception is thrown.
The code below demonstrates how to use the removeFirst
method:
import java.util.LinkedList;class LinkedListRemoveFirst {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);System.out.println("Removing first element of the list : " + list.removeFirst());System.out.println("The list is " + list);}}
In the code above:
LinkedList
class.import java.util.LinkedList;
LinkedList
object with the name list
.LinkedList<String> list = new LinkedList<>();
add
method of the list
object to add three elements ("1"
,"2"
,"3"
) to the list.list.add("1");
list.add("2");
list.add("3");
removeFirst
method of the list
object to remove the first element of the list. This method removes the first element of the list and returns the removed element.list.removeFirst(); // "1"
list; // ["2","3"]