Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the CopyOnWriteArrayList.add method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

CopyOnWriteArrayList is a thread-safe version of an ArrayList. For all the write operations, it makes a fresh copy underlying array and performs the operation in the cloned array. Due to this, the performance is lower when compared to ArrayList. Read more about CopyOnWriteArrayList here.

The add method of the CopyOnWriteArrayList class adds an element to the end of the CopyOnWriteArrayList.

Syntax

public boolean add(E e);

Parameters

The add method takes the element to be added to the list as a parameter.

Return value

The add method returns true if the element is added to the list.

Code

The code below demonstrates how to use the add method.

import java.util.concurrent.CopyOnWriteArrayList;
class Add {
public static void main( String args[] ) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("hello");
System.out.println("The list is " + list);
list.add("hi");
System.out.println("The list is " + list);
}
}

Explanation

In the code above, we:

  • Import the CopyOnWriteArrayList class.

  • Create a CopyOnWriteArrayList object with the name list.

  • Use the add method of the list object to add an element ("hello") to the list.

  • Then we print the list.

  • Use the add method of the list object to add another element ("hi") to the list.

  • Then we print the list.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring