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.
CopyOnWriteArrayListis a thread-safe version of anArrayList. For all the write operations likeaddandset, 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 aboutCopyOnWriteArrayListhere.
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 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());}}
Explanation
-
In line 1, we import the
CopyOnWriteArrayListclass. -
In line 4, we create a new
CopyOnWriteArrayListobject with the namelist. -
In lines 5-7, we add three elements (
1,2,3) tolistusing theadd()method. -
In line 8, we use the
toString()method to get the string representation oflist.