ArrayList clear() Method in Java with Examples
Last Updated :
02 Jun, 2023
The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so whenever this operation has been performed all elements of the corresponding ArrayList will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimization.
Syntax
public void clear()
Parameters
clear method does not need any parameters.
Return Type
It does not return any value as it removes all the elements in the list and makes it empty.
Tip: It does implement the following interfaces as follows: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
Example of ArrayList clear() Method
Example 1:
Java
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<Integer>( 4 );
arr.add( 1 );
arr.add( 2 );
arr.add( 3 );
arr.add( 4 );
System.out.println( "The list initially: " + arr);
arr.clear();
System.out.println(
"The list after using clear() method: " + arr);
}
}
|
Output
The list initially: [1, 2, 3, 4]
The list after using clear() method: []
Example 2:
In this example, we create a new ArrayList called animals and add some elements to it using the add() method. Then, we print the elements of the ArrayList.
Next, we call the clear() method to remove all elements from the ArrayList. Finally, we print the elements of the ArrayList again to demonstrate that it is now empty.
Java
import java.util.ArrayList;
public class Main {
public static void main(String[] args)
{
ArrayList<String> animals = new ArrayList<>();
animals.add( "Dog" );
animals.add( "Cat" );
animals.add( "Rabbit" );
animals.add( "Bird" );
System.out.println( "Animals: " + animals);
animals.clear();
System.out.println( "Animals after clearing: "
+ animals);
}
}
|
Output
Animals: [Dog, Cat, Rabbit, Bird]
Animals after clearing: []
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...