Last Updated : 29 Nov, 2024
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.
Example:
Java
// Java Program to Demonstrate
// List clear()
import java.util.*;
class Main
{
public static void main (String[] args)
{
// Created List
List<Integer> l=new ArrayList<Integer>();
// Adding Element
l.add(1);
l.add(2);
// Original List
System.out.println("Original : " + l);
// Clearing the List
l.clear();
// Printing the List
System.out.println("After Operation : " + l);
}
}
Original : [1, 2] After Operation : []Syntax of Method
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.
Example of List.clear() methodProgram 1:
Java
// 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> l = new ArrayList<String>(5);
// Use add() method to initially
// add elements in the list
l.add("Geeks");
l.add("For");
l.add("Geeks");
// Original List
System.out.println("Original : " + l);
// Removing elements from the List
l.clear();
// Printing the List
System.out.println("After Operation : " + l);
}
}
Original : [Geeks, For, Geeks] After Operation : []
Program 2:
Java
// 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> l = new ArrayList<Integer>(5);
// Use add() method to initially
// add elements in the list
l.add(10);
l.add(20);
l.add(30);
// Original List
System.out.println("Original : " + l);
// Removing elements from the List
l.clear();
// Printing the List
System.out.println("After Operation : " + l);
}
}
Original : [10, 20, 30] After Operation : []
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#clear()
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4