Last Updated : 11 Jul, 2025
The clear() method in the ArrayList class in Java is used to remove all elements from an ArrayList. After calling this method, the list becomes empty.
Example 1: Here, we will use the clear() method to clear elements from an ArrayList of Integers.
Java
// Java program to demonstrate clear() method
// in Integer ArrayList
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Creating an ArrayList of integers
ArrayList<Integer> n = new ArrayList<>();
// Adding elements to the ArrayList
n.add(10);
n.add(20);
n.add(30);
// Printing the original ArrayList
System.out.println("" + n);
// Clearing all elements from the ArrayList
n.clear();
System.out.println("" + n);
}
}
Syntax of clear() Method
public void clear()
Important Point: It does implement interfaces like Serializable, Cloneable, Iterable, Collection, List, RandomAccess.
Example 2: Here, we will use the clear() method to clear elements from an ArrayList of Strings.
Java
// Java program to demonstrate clear() method
// in ArrayList of Strings
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Creating an ArrayList of strings
ArrayList<String> a = new ArrayList<>();
// Adding elements to the ArrayList
a.add("Dog");
a.add("Cat");
a.add("Rabbit");
// Printing the original ArrayList
System.out.println("" + a);
// Clearing all elements
// from the ArrayList
a.clear();
// Printing the ArrayList after clearing
System.out.println("" + a);
}
}
[Dog, Cat, Rabbit] []
Example 3: Here, we will use the clear() method to clear elements from an ArrayList of Objects.
Java
// Java program to demonstrate clear() method
// in ArrayList of Objects
import java.util.ArrayList;
public class GFG {
static class Person {
String n;
Person(String n) {
this.n = n;
}
public String toString() {
return n;
}
}
public static void main(String[] args) {
// Create ArrayList of Person objects
ArrayList<Person> p = new ArrayList<>();
// Add objects
p.add(new Person("Ram"));
p.add(new Person("Shyam"));
// Print before clearing
System.out.println("" + p);
// Clear the ArrayList
p.clear();
// Print after clearing
System.out.println("" + p);
}
}
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