What is the LinkedList.addFirst method in Java?

The addFirst method can be used to add the element to the beginning of a LinkedList.

What is a LinkedList?

A LinkedList is a collection of linear data elements. Each element (or node) contains data and reference parts.

  • The data part has the value.
  • The reference part has the address link to the next element.

The elements are not indexed so random access like Array is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList is a doubly-linkedEach node contains three fields: two link fields(one for the previous element and another for the next element) and one data field. list implementation of the List and Deque interfaces. The LinkedList class present in the java.util package.

Syntax

public void addFirst(E e);

This method takes the element to be added to the list as an argument.

This method doesn’t return any value.

Code

The code below demonstrates how to use the addFirst method.

import java.util.LinkedList;
class LinkedListAddFirst {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.addFirst("3");
System.out.println("The list is " + list);
list.addFirst("2");
System.out.println("The list is " + list);
list.addFirst("1");
System.out.println("The list is " + list);
}
}

Explanation

In the code above:

  • In line 1, we imported the LinkedList class.

  • In line 4, we created a LinkedList object with the name list.

  • In line 5, we used the addFirst method of the list object to add an element ("3") to the beginning of the list. Then, we printed the list.

  • In line 7, we used the addFirst method to add an element ("2") to the beginning of the list. Then, we printed the list.

  • In line 10, we used the addFirst method to add an element ("1") to the beginning of the list.