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.
public boolean add(E e);
The add method takes the element to be added to the list as a parameter.
The add method returns true if the element is added to the list.
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);}}
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.