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
LinkedListis alist implementation of the List and Deque interfaces. The doubly-linked Each node contains three fields: two link fields(one for the previous element and another for the next element) and one data field. LinkedListclass present in thejava.utilpackage.
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
LinkedListclass. -
In line 4, we created a
LinkedListobject with the namelist. -
In line 5, we used the
addFirstmethod of thelistobject to add an element ("3") to the beginning of the list. Then, we printed the list. -
In line 7, we used the
addFirstmethod to add an element ("2") to the beginning of thelist. Then, we printed the list. -
In line 10, we used the
addFirstmethod to add an element ("1") to the beginning of thelist.