How to use ArrayList clear() Method in Java the Right Way

Published by user on

The user creates the ArrayList and does all sort of operations on the list. In most of the cases, it becomes essential to clear up some memory. ArrayList clear() method clears all the elements from the list and makes it empty. The performance of the clear() is excellent and time complexity is O(n). If you want to get rid of all the elements at once, then you can use this method. After the call returns, all the objects in the list become unreachable, and garbage collector clears them.

Let’s now look at the syntax.

public void clear()

clear() accepts no parameter and doesn’t return anything.

Look at the diagram to get more idea.

ArrayList clear

 

Program to demonstrate ArrayList clear()

In the below program we will,

  1. Create the ArrayList and add elements to it.
  2. Call clear() and check if the list becomes empty.
import java.util.ArrayList;

public class ArrayListClearExample {

	public static void main(String[] args) {
		ArrayList<Integer> numbers = new ArrayList<>();
		numbers.add(11);
		numbers.add(17);
		numbers.add(33);
		System.out.println("ArrayList element: " + numbers);
		numbers.clear();
		System.out.println("ArrayList elements after clear(): " + numbers);
	}
}

Output:

ArrayList element: [11, 17, 33]
ArrayList elements after clear(): []

That’s all in this article. Please share if you like it.

Further Reading:

ArrayList Reference.

Categories: Java