.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
: TheArrayList
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 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.