Java ArrayList.clear(): Emptying Lists & Managing Backing Capacity

The ArrayList.clear() method removes all elements from an ArrayList in O(n) time by setting every occupied slot in the internal array to null and resetting the list size to 0.

Related List Operations: After calling clear(), ArrayList.isEmpty() returns true and ArrayList.size() returns 0. To shrink the retained internal array capacity after clearing a large list, call ArrayList.trimToSize(). To remove only elements matching another collection, use ArrayList.removeAll().

1. Syntax, Method Signature & Internal Mechanics 🔝

Declared in java.util.ArrayList<E>:

 // Removes all elements from this list (returns void)
public void clear()
Aspect Specification Internal Behavior
Return Type void Modifies the target ArrayList in place.
Time Complexity O(n) Iterates from 0 to size - 1, assigning null so objects can be garbage-collected.
Backing Capacity Unchanged The internal Object[] array keeps its current allocated length for fast reuse.

2. Basic Emptying & Reusing an ArrayList 🔝

Calling languages.clear() empties all existing elements while keeping the languages object ready to accept new ArrayList.add() calls immediately:

import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("PHP");
languages.add("Python");
System.out.println(languages);  // [Java, PHP, Python]

 // Remove all elements
languages.clear();
System.out.println(languages);  // []

 // Reuse the same ArrayList instance
languages.add("Java");
System.out.println(languages);  // [Java]

Terminal Output:

[Java, PHP, Python]
[]
[Java]

3. Verifying Empty State with size() & isEmpty() 🔝

Immediately after clear() completes, size() returns 0 and isEmpty() returns true:

ArrayList<String> tasks = new ArrayList<>();
tasks.add("Compile");
tasks.add("Deploy");
System.out.println("Before: size=" + tasks.size() + ", isEmpty=" + tasks.isEmpty());

tasks.clear();
System.out.println("After:  size=" + tasks.size() + ", isEmpty=" + tasks.isEmpty());

Terminal Output:

Before: size=2, isEmpty=false
After:  size=0, isEmpty=true

4. Memory Management: Pairing clear() with trimToSize() 🔝

Although clear() nulls out the element references (allowing the referenced objects to be garbage-collected), the internal Object[] array itself remains at its peak capacity. If a list experienced a one-time size spike and will stay small or empty, call trimToSize() after clear() to release the array buffer:

ArrayList<Integer> spikeBuffer = new ArrayList<>(10000);
for (int i = 0; i < 5000; i++) spikeBuffer.add(i);

spikeBuffer.clear();       // Nulls 5000 references (size = 0, capacity still 10000)
spikeBuffer.trimToSize();  // Shrinks backing Object[] array down to length 0
System.out.println("Cleared & trimmed size: " + spikeBuffer.size());

Terminal Output:

Cleared & trimmed size: 0

5. Clearing a Slice of Elements via subList().clear() 🔝

To clear only a specific index range without writing a loop, chain subList(fromIndex, toIndex) with .clear() (which delegates to removeRange() in a single shift):

import java.util.Arrays;

ArrayList<String> logs = new ArrayList<>(Arrays.asList("L0", "L1", "L2", "L3", "L4"));
 // Clear only elements at indices 1, 2, and 3 (end index 4 is exclusive)
logs.subList(1, 4).clear();
System.out.println("Remaining logs: " + logs);

Terminal Output:

Remaining logs: [L0, L4]

6. Comparison: clear() vs removeAll() vs new ArrayList<>() 🔝

Choosing the fastest and cleanest way to reset a list:

Method / Idiom Complexity When to Use
list.clear() O(n) Best when reusing the same list instance and its allocated array capacity.
list = new ArrayList<>() O(1) Best when the old list must remain intact for other references or had a massive one-time spike.
list.removeAll(list) O(n^2) Never use to empty a list! Performs a linear scan for every element.

7. Production Recipe: Reusable Batch Buffer in Stream Loops 🔝

Calling batch.clear() after flushing each chunk reuses the exact same backing array across thousands of batches without triggering GC allocation churn:

public class ReusableBatchFlush {
    public static void main(String[] args) {
        ArrayList<Integer> batch = new ArrayList<>(3);
        for (int i = 1; i <= 6; i++) {
            batch.add(i);
            if (batch.size() == 3) {
                System.out.println("Flushing batch: " + batch);
                batch.clear();  // Reuse backing array for next batch
            }
        }
    }
}

Terminal Output:

Flushing batch: [1, 2, 3]
Flushing batch: [4, 5, 6]

8. Practical Recipe: Taking a Snapshot Copy Before clear() 🔝

When archiving a batch into a outer list before resetting the working buffer, wrap the buffer in new ArrayList<>(current) (or clone()) before calling current.clear():

public class SafeSnapshotBeforeClear {
    public static void main(String[] args) {
        ArrayList<ArrayList<String>> history = new ArrayList<>();
        ArrayList<String> current = new ArrayList<>();
        current.add("Tx-101");
        current.add("Tx-102");

         // Save an independent copy BEFORE clearing current!
        history.add(new ArrayList<>(current));
        current.clear();

        System.out.println("Saved history: " + history);
        System.out.println("Active buffer: " + current);
    }
}

Terminal Output:

Saved history: [[Tx-101, Tx-102]]
Active buffer: []

9. Common Developer Pitfalls & Traps 🔝

The Shared Reference Trap: history.add(batch); batch.clear();

If you add batch directly into history without copying it and then call batch.clear(), the element inside history points to the exact same ArrayList object and becomes empty too! Always store new ArrayList<>(batch) when archiving.

Calling clear() on an Unmodifiable or Fixed-Size List

Calling clear() on a list returned by Arrays.asList(...) or List.of(...) throws an UnsupportedOperationException. Wrap it in new ArrayList<>(Arrays.asList(...)) if you need a mutable list that supports clear().

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListClearFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
        list.clear();
        if (list.isEmpty() && list.size() == 0) {
            System.out.println("Check 1 Passed: clear() reset size to 0.");
        }
        list.addAll(Arrays.asList("X", "Y", "Z"));
        list.subList(0, 2).clear();
        if (list.size() == 1 && list.get(0).equals("Z")) {
            System.out.println("Check 2 Passed: subList(0, 2).clear() left [Z].");
        }
        System.out.println("All ArrayList.clear() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: clear() reset size to 0.
Check 2 Passed: subList(0, 2).clear() left [Z].
All ArrayList.clear() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Does ArrayList.clear() free memory for garbage collection?

Yes for the elements: clear() overwrites every array slot with null so the element objects can be garbage-collected if nothing else references them. However, the internal Object[] array itself is retained unless you also call trimToSize().

Is it faster to call list.clear() or list = new ArrayList<>()?

If you are going to refill the list with a similar number of elements, list.clear() is faster overall because it avoids reallocating and growing the backing array from scratch.

What happens if I call clear() on an already empty ArrayList?

It safely does nothing in O(1) time (the internal loop 0 < 0 does not execute).

Why should I never use list.removeAll(list) instead of list.clear()?

list.clear() runs in a single linear pass (O(n)), whereas list.removeAll(list) checks membership for every element, taking O(n^2) time.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer