What is the CopyOnWriteArrayList.size 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 slower that ArrayList. Read more about CopyOnWriteArrayList here.

The size method can be used to get the sizeNumber of elements present in the list of the CopyOnWriteArrayList object.

Syntax

public int size()

Parameters

This method doesn’t take in any arguments.

Return value

This method returns the number of elements present in the list as an integer.

Code

The code below demonstrates how to use the size method.

//importing the CopyOnWriteArrayList class
import java.util.concurrent.CopyOnWriteArrayList;
class Size {
public static void main( String args[] ) {
//Creating the CopyOnWriteArrayList Object
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
// Using the add method to add elements in list
list.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 case
System.out.println("The size of list is : " + list.size());
}
}

Explanation

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.

Free Resources