Java ArrayList addFirst() Method

The ArrayList.addFirst() method was introduced in Java 21 and is used to add an element to the beginning of the ArrayList. 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 to the Beginning of the List
    • Handling IndexOutOfBoundsException
  4. Real-World Use Case
  5. Conclusion

Introduction

In Java 21, the ArrayList class has been enhanced with the addFirst() method, which allows you to add an element to the beginning of the list. This method is particularly useful when you need to prioritize certain elements by adding them to the start of the list.

addFirst Method Syntax

The syntax for the addFirst method is as follows:

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

Examples

Adding an Element to the Beginning of the List

The addFirst method adds the specified element to the beginning of the ArrayList.

Example

import java.util.ArrayList;

public class AddFirstExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Banana");
        list.add("Orange");

        // Add an element to the beginning of the list
        list.addFirst("Apple");

        System.out.println("ArrayList after addFirst: " + list);
    }
}

Output:

ArrayList after addFirst: [Apple, Banana, Orange]

Handling IndexOutOfBoundsException

While the addFirst method is straightforward, it's always good practice to handle potential exceptions in your code to ensure robustness.

Example

import java.util.ArrayList;

public class AddFirstWithExceptionHandling {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();

        try {
            // Add an element to the beginning of the list
            list.addFirst("Apple");

            System.out.println("ArrayList after addFirst: " + list);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

ArrayList after addFirst: [Apple]

Real-World Use Case

Task Management System

In a task management system, tasks can be prioritized by adding them to the beginning of the list using the addFirst() method.

Example

import java.util.ArrayList;

class Task {
    String name;
    boolean isHighPriority;

    Task(String name, boolean isHighPriority) {
        this.name = name;
        this.isHighPriority = isHighPriority;
    }

    @Override
    public String toString() {
        return name + (isHighPriority ? " (High Priority)" : "");
    }
}

public class TaskManager {
    public static void main(String[] args) {
        ArrayList<Task> tasks = new ArrayList<>();

        // Add regular tasks
        tasks.add(new Task("Write report", false));
        tasks.add(new Task("Prepare presentation", false));

        // Add a high priority task at the beginning
        tasks.addFirst(new Task("Fix critical bug", true));

        // Display all tasks
        System.out.println("Task List:");
        tasks.forEach(task -> System.out.println(task));
    }
}

Output:

Task List:
Fix critical bug (High Priority)
Write report
Prepare presentation

Conclusion

The ArrayList.addFirst() method in Java 21 provides a convenient way to add elements to the beginning of an ArrayList. By understanding how to use this method, you can efficiently manage the contents of your lists in Java applications, especially in scenarios where prioritization is important. Whether you are adding elements to the start of the list or handling potential exceptions, the addFirst() method offers a straightforward and effective solution.

Comments