Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

tostring
java
communitycreator

What is the CopyOnWriteArrayList.toString method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
}
}
Using toString method

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.

RELATED TAGS

tostring
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring