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 anArrayList
. For all the write operations likeadd
andset
, 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 toArrayList
. Read more aboutCopyOnWriteArrayList
here.
public String toString()
This method doesn’t take any arguments.
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.
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 elementsCopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();// add elements to the listlist.add(1);list.add(2);list.add(3);// use toString method covert the list to stringSystem.out.println(list.toString());}}
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
.