.clear()

Anonymous contributor's avatar
Anonymous contributor
Published Jun 27, 2024
Contribute to Docs

The .clear() method in Java removes all elements from an ArrayList. After invoking this method, the ArrayList gets empty, but its capacity remains unchanged. The method does not return a value.

Syntax

myArrayList.clear();
  • myArrayList: The ArrayList to be cleared.

Example

The example below shows the use of the .clear() method:

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> fruits = new ArrayList<>();
// Adding elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Printing the ArrayList
System.out.println("Fruits: " + fruits);
// Clearing the ArrayList
fruits.clear();
// Printing the cleared ArrayList
System.out.println("Fruits after .clear(): " + fruits);
}
}

Here is the output for the code above:

Fruits: [Apple, Banana, Cherry]
Fruits after .clear(): []

All contributors

Contribute to Docs

Learn Java on Codecademy