Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
add method

What is CopyOnWriteArrayList.add method() in Java?

abhilash

In the CopyOnWriteArrayList class, the whole content is duplicated into a new internal copy when we use any altering method. This includes methods such as add() or delete(). The add() is used to add an element at the end of the list or the specified index.

The CopyOnWriteArrayList class is defined in the java.util.concurrent package. To import the CopyOnWriteArrayList class use the following statement:

import java.util.concurrent.CopyOnWriteArrayList;

add(E e)


public boolean add(E e)

Parameters

  • E e: The element to add.

Return value

This method returns true if the list changes/modifies due to this operation. Otherwise, it returns false.

add(int index, E element)


public void add(int index, E element)

Parameters

  • int index: The index at which the element should be inserted.
  • E element: The element to add.

Return value

This method doesn’t return anything.

import java.util.concurrent.CopyOnWriteArrayList;

public class Main{

    public static void main(String[] args) {
        // Create the CopyOnWriteArrayList object
        CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();

        // add elements to the end of the copyOnWriteArrayList
        copyOnWriteArrayList.add("inital-value");
        copyOnWriteArrayList.add("hello");

        // add element at the specified index
        int index = 1;
        copyOnWriteArrayList.add(index, "educative");

        // print the list
        System.out.println("List - " + copyOnWriteArrayList);
    }
}
Implementation of the "add" method

Explanation

  • Line 1: We import the CopyOnWriteArrayList class.
  • Line 7: We create a CopyOnWriteArrayList object named copyOnWriteArrayList.
  • Lines 10-11: We add elements to the end of the copyOnWriteArrayList.
  • Line 14: We define the index at which the element has to be inserted.
  • Line 15: The index defined in Line 14 and the element to be inserted are passed as arguments to add() method.
  • Line 18: We print the copyOnWriteArrayList.

RELATED TAGS

java
communitycreator
add method
RELATED COURSES

View all Courses

Keep Exploring