ArrayList clear() Method in Java with Examples (original) (raw)

Last Updated : 10 Dec, 2024

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);
}

}

`

Output

[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);
}

}

`