The clear() of java.util.Collection interface is used to clear the Collection upon which it is called. This method does not take any parameter and does not returns any value.
Syntax:
Collection.clear()
Parameters: This method do not accept any parameter
Return Value: This method does not return any value.
Exceptions: This method throws following exceptions:
- UnsupportedOperationException: if the add operation is not supported by this collection
Below examples illustrate the Collection clear() method:
Example 1: Using LinkedList Class
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String args[])
{
Collection<String> list = new LinkedList<String>();
list.add("Geeks");
list.add("for");
list.add("Geeks");
System.out.println("The list is: " + list);
list.clear();
System.out.println("The new List is: " + list);
}
}
|
Output:
The list is: [Geeks, for, Geeks]
The new List is: []
Example 2: Using ArrayDeque Class
import java.util.*;
public class ArrayDequeDemo {
public static void main(String args[])
{
Collection<String> de_que = new ArrayDeque<String>();
de_que.add("Welcome");
de_que.add("To");
de_que.add("Geeks");
de_que.add("4");
de_que.add("Geeks");
System.out.println("ArrayDeque: " + de_que);
de_que.clear();
System.out.println("The new ArrayDeque is: "
+ de_que);
}
}
|
Output:
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The new ArrayDeque is: []
Example 3: Using ArrayList Class
import java.io.*;
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args)
{
Collection<Integer> arrlist = new ArrayList<Integer>(5);
arrlist.add(15);
arrlist.add(20);
arrlist.add(25);
System.out.println("ArrayList: " + arrlist);
arrlist.clear();
System.out.println("The new ArrayList is: "
+ arrlist);
}
}
|
Output:
ArrayList: [15, 20, 25]
The new ArrayList is: []
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#clear–
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
29 Nov, 2018
Like Article
Save Article