ArrayList clear() – Empty ArrayList in 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() {

    // 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<>(); 

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

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.