The addFirst method can be used to add the element to the beginning of a LinkedList.
LinkedList?A LinkedList is a collection of linear data elements. Each element (or node) contains data and reference parts.
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.
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.
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);}}
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.