Java LinkedList addFirst()

In this guide, you will learn about the LinkedList addFirst() method in Java programming and how to use it with an example.

1. LinkedList addFirst() Method Overview


The addFirst() method of the LinkedList class in Java is used to insert the given element at the beginning of the list. LinkedList is part of Java's collections framework and implements the List and Deque interfaces.


public void addFirst(E e)


- e: the element to add.

Key Points:

- The addFirst() method inserts the specified element at the beginning of the list.

- The method throws NullPointerException if the specified element is null and this list does not permit null elements.

- This operation is equivalent to add(0, e).

- The method belongs to java.util.LinkedList class.

2. LinkedList addFirst() Method Example

import java.util.LinkedList;

public class LinkedListAddFirstExample {

    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();

        // Adding elements to the LinkedList
        linkedList.add("Element 1");
        linkedList.add("Element 2");
        linkedList.add("Element 3");

        // Printing the original LinkedList
        System.out.println("Original LinkedList: " + linkedList);

        // Using addFirst() to add an element at the beginning of the LinkedList
        linkedList.addFirst("Element 0");
        System.out.println("LinkedList after addFirst(): " + linkedList);

        // Adding another element using addFirst()
        linkedList.addFirst("Element -1");
        System.out.println("LinkedList after another addFirst(): " + linkedList);


Original LinkedList: [Element 1, Element 2, Element 3]
LinkedList after addFirst(): [Element 0, Element 1, Element 2, Element 3]
LinkedList after another addFirst(): [Element -1, Element 0, Element 1, Element 2, Element 3]


In this example, a LinkedList is created and populated with some elements. 

The addFirst() method is then used to insert elements at the beginning of the LinkedList. The output shows the original LinkedList, and the LinkedList after each call to addFirst(), demonstrating that the new elements are indeed added at the beginning of the list.