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 slower thatArrayList
. Read more aboutCopyOnWriteArrayList
here.
The size
method can be used to get the CopyOnWriteArrayList
object.
public int size()
This method doesn’t take in any arguments.
This method returns the number of elements present in the list as an integer.
The code below demonstrates how to use the size
method.
//importing the CopyOnWriteArrayList classimport java.util.concurrent.CopyOnWriteArrayList;class Size {public static void main( String args[] ) {//Creating the CopyOnWriteArrayList ObjectCopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();// Using the add method to add elements in listlist.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);// The size method will return the size of the list which is 3 in this caseSystem.out.println("The size of list is : " + list.size());}}
In the code above, we have:
Imported the
CopyOnWriteArrayList
class.
Created a CopyOnWriteArrayList
object with the name list
.
Used the add
method of the list object to add three elements ("1","2","3"
) to the list.
Used the size
method of the list object to get the size of the list. In our case, 3
will be returned because the list
object has 3 elements.