Return empty ArrayList java

ArrayList clear() method is used to removes all of the elements from the list. The list will be empty after this call returns.

1. ArrayList clear() syntax

clear() method does simple thing. It iterates the backing array inside arraylist and assign all elements 'null' value and set the size attribute to '0'.

public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }
  • Method parameter none.
  • Method returns void.
  • Method throws none.

2. ArrayList clear() example

Java program to make empty an arraylist using clear() method.

import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("A"); arrayList.add("B"); arrayList.add("C"); arrayList.add("D"); System.out.println(arrayList); arrayList.clear(); System.out.println(arrayList); } }

Program output.

[A, B, C, D] []

3. ArrayList clear vs new

An empty arraylist has zero elements. A new arraylist also has zero elements. But there is differenece between them.

The difference between an empty and a new arraylist is the size of backing array. As clear() method does not resize the backing array, so after clear method you may have a list which has backing array of a larger size (if list was pretty big before clear() method was called).

Except above difference in capacity, there is no difference between both kind of lists.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Let us know if you liked the post. Thats the only way we can improve.
Yes
No