Java Collection clear() Method

The clear() method of Java Collection Interface removes all of the elements from this collection. It returns a Boolean value 'true', if it successfully empties the collection.

Syntax

Parameters

NA

Throws

UnsupportedOperationException- if the clear operation is not supported by this collection.

Example 1

Test it Now

Output:

Collection : [23, 123, 56]
After applying clear() method :  
Collection : []

Example 2

Output:

1. Sugar
2. Salt
3. Potato
4. Rice
Is Your shopping done.?
true/false : true
Your queue has been emptied successfully.

Process finished with exit code 0 

Example 3

Test it Now

Output:

Exception in thread "main" java.lang.NullPointerException
	at java.util.concurrent.LinkedBlockingDeque.offerLast(LinkedBlockingDeque.java:357)
	at java.util.concurrent.LinkedBlockingDeque.addLast(LinkedBlockingDeque.java:334)
	at java.util.concurrent.LinkedBlockingDeque.add(LinkedBlockingDeque.java:633)
	at com.javaTpoint.JavaCollectionClearExample3.main(JavaCollectionClearExample3.java:9)
Next TopicJava Collection




Latest Courses