What is the CopyOnWriteArrayList.add method in Java?
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
CopyOnWriteArrayListclass. -
Create a
CopyOnWriteArrayListobject with the namelist. -
Use the
addmethod of thelistobject to add an element ("hello") to the list. -
Then we print the list.
-
Use the
addmethod of thelistobject to add another element ("hi") to the list. -
Then we print the list.