What is the CopyOnWriteArrayList.toString method in Java?

The toString() method will return the string representation of the CopyOnWriteArrayList object with the string representation of each element in the list.

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

Syntax

public String toString()

Parameters

This method doesn’t take any arguments.

Return value

This method returns a string. This string contains the elements of the list in the insertion order enclosed between [] and separated by a comma. Internally, the elements are converted to a string using the String.valueOf(Object) method.

Code

The code below demonstrates how the toString() method can be used.

import java.util.concurrent.CopyOnWriteArrayList;
class ToStringExample {
public static void main( String args[] ) {
// create a CopyOnWriteArrayList object which can contain integer elements
CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
// add elements to the list
list.add(1);
list.add(2);
list.add(3);
// use toString method covert the list to string
System.out.println(list.toString());
}
}

Explanation

  • In line 1, we import the CopyOnWriteArrayList class.

  • In line 4, we create a new CopyOnWriteArrayList object with the name list.

  • In lines 5-7, we add three elements (1,2,3) to list using the add() method.

  • In line 8, we use the toString() method to get the string representation of list.