Java .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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

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

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours