ArrayList clear() Method in Java with Examples
Last Updated :
10 Dec, 2024
Improve
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 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);
}
}
Output
[10, 20, 30] []
Syntax of clear() Method
public void clear()
- Parameter: The clear() method does not need any parameters.
- Return Type: It does not return any value as it removes all the elements in the list and makes it empty.
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 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);
}
}
Output
[Dog, Cat, Rabbit] []
Example 3: Here, we will use the clear() method to clear elements from an ArrayList of Objects.
// 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);
}
}
Output
[Ram, Shyam] []