Java LinkedList addFirst() Method

The LinkedList.addFirst() method in Java is used to add an element at the beginning of a LinkedList. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality.

Table of Contents

  1. Introduction
  2. addFirst Method Syntax
  3. Examples
    • Adding an Element at the Beginning
    • Handling Null Values
  4. Conclusion

Introduction

The LinkedList.addFirst() method is a member of the LinkedList class in Java. It allows you to add an element at the beginning of the LinkedList, making it the first element in the list. This method is particularly useful for implementing stack-like structures or adding elements in a specific order.

addFirst Method Syntax

The syntax for the addFirst method is as follows:

public void addFirst(E e)
  • e: The element to be added to the beginning of the LinkedList.

Examples

Adding an Element at the Beginning

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

Example

import java.util.LinkedList;

public class AddFirstExample {
    public static void main(String[] args) {
        // Creating a LinkedList of Strings
        LinkedList<String> list = new LinkedList<>();

        // Adding elements to the LinkedList
        list.add("Apple");
        list.add("Banana");

        // Adding an element at the beginning of the LinkedList
        list.addFirst("Orange");

        // Printing the LinkedList
        System.out.println("LinkedList: " + list);
    }
}

Output:

LinkedList: [Orange, Apple, Banana]

Handling Null Values

The addFirst method can handle null values. Adding a null value to a LinkedList will include null as the first element in the list.

Example

import java.util.LinkedList;

public class AddFirstExample {
    public static void main(String[] args) {
        // Creating a LinkedList of Strings
        LinkedList<String> list = new LinkedList<>();

        // Adding elements to the LinkedList
        list.add("Apple");
        list.add("Banana");

        // Adding a null element at the beginning of the LinkedList
        list.addFirst(null);

        // Printing the LinkedList
        System.out.println("LinkedList: " + list);
    }
}

Output:

LinkedList: [null, Apple, Banana]

Conclusion

The LinkedList.addFirst() method in Java is a simple and effective way to add elements to the beginning of a LinkedList. By understanding how to use this method, you can efficiently manage collections of objects in your Java applications. Whether you are adding elements to implement stack-like behavior or handling potential null values, the addFirst method provides a flexible solution for these tasks.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top