List clear() method in Java with Examples
The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it justs removes all of the elements from the List.
Syntax:
public void clear()
Parameter: This method accepts does not accepts any parameter.
Return Value: The return type of the function is void and it does not returns anything.
Exceptions: This method throws an UnsupportedOperationException if the clear() operation is not supported by this list.
Below programs illustrate the List.clear() method:
Program 1:
// Java code to illustrate clear() method import java.io.*; import java.util.*; public class ListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<String> list = new ArrayList<String>(5); // use add() method to initially // add elements in the list list.add("Geeks"); list.add("For"); list.add("Geeks"); // Remove all elements from the List list.clear(); // print the List System.out.println(list); } } |
[]
Program 2:
// Java code to illustrate clear() method import java.io.*; import java.util.*; public class ListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<Integer> list = new ArrayList<Integer>(5); // use add() method to initially // add elements in the list list.add(10); list.add(20); list.add(30); // clear the list list.clear(); // prints all the elements available in list System.out.println(list); } } |
[]
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#clear()
Recommended Posts:
- Set clear() method in Java with Examples
- AbstractMap clear() Method in Java with Examples
- EnumMap clear() Method in Java with Examples
- IntBuffer clear() method in Java with Examples
- Properties clear() method in Java with Examples
- Collection clear() method in Java with Examples
- Calendar clear() Method in Java with Examples
- AbstractCollection clear() Method in Java with Examples
- SortedSet clear() method in Java with Examples
- ConcurrentSkipListMap clear() method in Java with Examples
- LongBuffer clear() method in Java with Examples
- LinkedHashSet clear() method in Java with Examples
- AbstractList clear() method in Java with Examples
- SortedMap clear() method in Java with Examples
- AbstractQueue clear() method in Java with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



