Java CopyOnWriteArrayList add() Method

The CopyOnWriteArrayList.add() method in Java is used to add elements to a CopyOnWriteArrayList.

Table of Contents

  1. Introduction
  2. add Method Syntax
  3. Examples
    • Adding Elements to a CopyOnWriteArrayList
    • Adding Elements at a Specific Position
  4. Real-World Use Case
    • Example: Managing a Thread-Safe List of Users
  5. Conclusion

Introduction

The CopyOnWriteArrayList is a thread-safe variant of ArrayList in Java. It is part of the java.util.concurrent package and is designed for scenarios where read operations are more frequent than write operations. The add method allows you to add elements to the list. The CopyOnWriteArrayList achieves thread safety by creating a new copy of the array whenever it is modified.

add() Method Syntax

There are two variations of the add method:

Basic Add

public boolean add(E e)
  • The method takes one parameter:
    • e of type E, which represents the element to be added to the list.
  • The method returns true if the element is successfully added.

Add at a Specific Position

public void add(int index, E element)
  • The method takes two parameters:
    • index of type int, which represents the position at which the element is to be added.
    • element of type E, which represents the element to be added to the list.
  • The method does not return a value.

Examples

Adding Elements to a CopyOnWriteArrayList

The basic add method can be used to add elements to a CopyOnWriteArrayList.

Example

import java.util.concurrent.CopyOnWriteArrayList;

public class AddExample {
    public static void main(String[] args) {
        // Creating a CopyOnWriteArrayList with String elements
        CopyOnWriteArrayList<String> names = new CopyOnWriteArrayList<>();

        // Adding elements to the CopyOnWriteArrayList
        names.add("Ravi");
        names.add("Priya");
        names.add("Vijay");

        // Printing the CopyOnWriteArrayList
        System.out.println("CopyOnWriteArrayList: " + names);
    }
}

Output:

CopyOnWriteArrayList: [Ravi, Priya, Vijay]

Adding Elements at a Specific Position

The add method can also be used to add elements at a specific position in the CopyOnWriteArrayList.

Example

import java.util.concurrent.CopyOnWriteArrayList;

public class AddAtIndexExample {
    public static void main(String[] args) {
        // Creating a CopyOnWriteArrayList with String elements
        CopyOnWriteArrayList<String> names = new CopyOnWriteArrayList<>();

        // Adding elements to the CopyOnWriteArrayList
        names.add("Ravi");
        names.add("Vijay");

        // Adding an element at a specific position
        names.add(1, "Priya");

        // Printing the CopyOnWriteArrayList
        System.out.println("CopyOnWriteArrayList: " + names);
    }
}

Output:

CopyOnWriteArrayList: [Ravi, Priya, Vijay]

Real-World Use Case

Example: Managing a Thread-Safe List of Users

A common real-world use case for CopyOnWriteArrayList is managing a thread-safe list of users in a concurrent environment.

Example

import java.util.concurrent.CopyOnWriteArrayList;

public class UserListManager {
    public static void main(String[] args) {
        // Creating a CopyOnWriteArrayList to manage user names
        CopyOnWriteArrayList<String> userList = new CopyOnWriteArrayList<>();

        // Adding user names to the CopyOnWriteArrayList
        userList.add("Ravi");
        userList.add("Priya");
        userList.add("Vijay");

        // Simulating concurrent read and write operations
        Thread readerThread = new Thread(() -> {
            for (String user : userList) {
                System.out.println("Reading user: " + user);
            }
        });

        Thread writerThread = new Thread(() -> {
            userList.add("Anita");
            System.out.println("Added user: Anita");
        });

        // Starting the threads
        readerThread.start();
        writerThread.start();

        // Waiting for the threads to finish
        try {
            readerThread.join();
            writerThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Printing the final user list
        System.out.println("Final user list: " + userList);
    }
}

Output:

Reading user: Ravi
Reading user: Priya
Reading user: Vijay
Added user: Anita
Final user list: [Ravi, Priya, Vijay, Anita]

In this example, CopyOnWriteArrayList is used to manage a thread-safe list of user names, allowing concurrent read and write operations without compromising data integrity.

Conclusion

The CopyOnWriteArrayList.add() method in Java provides a way to add elements to a CopyOnWriteArrayList in a thread-safe manner. By understanding how to use this method, you can efficiently manage collections of elements in your Java applications, especially in concurrent environments. The method allows you to handle both basic and position-specific insertions, making it a versatile tool for data management in multi-threaded scenarios.

Comments