List clear() method in Java with Examples
Last Updated :
24 May, 2023
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 just 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
import java.io.*;
import java.util.*;
public class ListDemo {
public static void main(String[] args)
{
List<String> list = new ArrayList<String>( 5 );
list.add("Geeks");
list.add("For");
list.add("Geeks");
list.clear();
System.out.println(list);
}
}
|
Program 2:
Java
import java.io.*;
import java.util.*;
public class ListDemo {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>( 5 );
list.add( 10 );
list.add( 20 );
list.add( 30 );
list.clear();
System.out.println(list);
}
}
|
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#clear()
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...