Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the CopyOnWriteArrayList.clear 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.

Answers Code

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

The clear method can be used to delete all the elements of the CopyOnWriteArrayList object. After calling this method, the list becomes empty.

Syntax

public void clear();

This method doesn’t take any parameters and doesn’t return any value.

Code

The code below demonstrates the use of the clear method.

import java.util.concurrent.CopyOnWriteArrayList;
class Clear {
public static void main( String args[] ) {
// created a new set which can have string type elements
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
// adding 3 elements to the list
list.add("1");
list.add("2");
list.add("3");
System.out.println("The list is " + list);
// calling clear method to remove all elements of the list
list.clear();
System.out.println("After calling the clear method the list is " + list);
}
}
Using clear method

Explanation

In the code above,

  • In line 1: Import the CopyOnWriteArrayList class.

  • In line 5: Create a CopyOnWriteArrayList object named list.

  • In line 7-9: Use the add method of the list object to add three elements 1, 2, and 3 to the list.

  • In line 13: Use the clear method of the list object to remove all the list elements. After calling the clear method, the list becomes empty.

RELATED TAGS

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.

Answers Code
Keep Exploring