Java .clear()
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: TheArrayListto 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 ArrayListArrayList<String> fruits = new ArrayList<>();// Adding elements to the ArrayListfruits.add("Apple");fruits.add("Banana");fruits.add("Cherry");// Printing the ArrayListSystem.out.println("Fruits: " + fruits);// Clearing the ArrayListfruits.clear();// Printing the cleared ArrayListSystem.out.println("Fruits after .clear(): " + fruits);}}
Here is the output for the code above:
Fruits: [Apple, Banana, Cherry]Fruits after .clear(): []
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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