Java ArrayList.isEmpty(): Testing for Zero Elements Safely

The ArrayList.isEmpty() method returns true if the list contains zero elements (size() == 0), and false if at least one element is present.

Related List Operations: Adding an element with ArrayList.add() transitions isEmpty() from true to false, while emptying the list with ArrayList.clear() resets isEmpty() back to true. Always check !list.isEmpty() before calling list.get(0) or list.remove(0).

1. Syntax, Method Signature & Internal Implementation 🔝

Declared in java.util.ArrayList<E> (implementing Collection.isEmpty()):

 // Returns true if this list contains no elements (size == 0)
public boolean isEmpty()
Aspect Specification Operational Rule
Return Value boolean true if this list contains no elements; false otherwise.
OpenJDK Source return size == 0; Directly compares the internal int size field against 0.
Time Complexity O(1) Instant constant-time check regardless of backing array capacity.

2. Basic Check Before and After Adding Elements 🔝

A newly constructed ArrayList has zero elements, so isEmpty() returns true. As soon as elements are added via add(), the list is no longer empty and isEmpty() returns false:

import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<String>();
System.out.println("Before add: " + languages.isEmpty());  // true
languages.add("Java");
languages.add("PHP");
languages.add("Python");
System.out.println("After add:  " + languages.isEmpty());  // false

ArrayList<Integer> marks = new ArrayList<Integer>();
System.out.println("Marks empty? " + marks.isEmpty());     // true
marks.add(55);
marks.add(54);
System.out.println("Marks empty? " + marks.isEmpty());     // false

Terminal Output:

Before add: true
After add:  false
Marks empty? true
Marks empty? false

3. Does a List Containing null Count as Empty? 🔝

No! If you call list.add(null), the list now holds 1 element (whose value happens to be a null reference). Consequently, size() is 1 and isEmpty() returns false:

ArrayList<String> listWithNull = new ArrayList<>();
listWithNull.add(null);  // 1 element added (whose value is null)

System.out.println("size():    " + listWithNull.size());     // 1
System.out.println("isEmpty(): " + listWithNull.isEmpty());  // false!

Terminal Output:

size():    1
isEmpty(): false!

4. Pre-Allocated Capacity & clear() Lifecycle 🔝

isEmpty() only inspects the logical element count, never the internal array capacity. Pre-allocating capacity with new ArrayList<>(100) or ensureCapacity(100) still leaves isEmpty() as true, and calling clear() resets a populated list back to isEmpty() == true:

ArrayList<String> buffer = new ArrayList<>(100);  // Capacity 100, size 0
System.out.println("New with capacity 100 -> isEmpty(): " + buffer.isEmpty());  // true

buffer.add("Job-1");
System.out.println("After add('Job-1')    -> isEmpty(): " + buffer.isEmpty());  // false

buffer.clear();
System.out.println("After buffer.clear()  -> isEmpty(): " + buffer.isEmpty());  // true

Terminal Output:

New with capacity 100 -> isEmpty(): true
After add('Job-1')    -> isEmpty(): false
After buffer.clear()  -> isEmpty(): true

5. Exception Handling: Null List Reference vs Empty List 🔝

An uninitialized variable (ArrayList<String> list = null;) is not an empty list—it is a null pointer. Calling list.isEmpty() on a null variable throws a NullPointerException:

ArrayList<String> uninitialized = null;

try {
    uninitialized.isEmpty();  // Crash: calling a method on null!
} catch (NullPointerException ex) {
    System.out.println("Caught NullPointerException on null reference!");
}

Terminal Output:

Caught NullPointerException on null reference!

6. Comparison: Empty, Null & Size Checks in Java 🔝

Understanding the exact difference between common list state expressions:

Expression Safe on null Reference? Meaning & Recommendation
list.isEmpty() No (throws NPE) Preferred idiom when list is known to be non-null.
list.size() == 0 No (throws NPE) Equivalent on ArrayList, but less expressive than isEmpty().
list == null || list.isEmpty() Yes (Short-circuits) Standard defensive guard for external method parameters.

7. Production Recipe: Null-Safe isNullOrEmpty() Utility 🔝

Using short-circuit evaluation c == null || c.isEmpty() protects service methods against both null references and empty collections:

import java.util.Collection;

public class CollectionGuard {
    public static boolean isNullOrEmpty(Collection<?> c) {
        return c == null || c.isEmpty();
    }
    public static void main(String[] args) {
        ArrayList<String> a = null;
        ArrayList<String> b = new ArrayList<>();
        System.out.println("null list:  " + isNullOrEmpty(a));
        System.out.println("empty list: " + isNullOrEmpty(b));
    }
}

Terminal Output:

null list:  true
empty list: true

8. Practical Recipe: Draining a Work Stack with while (!isEmpty()) 🔝

Pairing while (!stack.isEmpty()) with stack.remove(stack.size() - 1) processes and removes elements in O(1) time per item until the list is empty:

public class LifoStackDrain {
    public static void main(String[] args) {
        ArrayList<String> stack = new ArrayList<>(Arrays.asList("Step-1", "Step-2", "Step-3"));
        while (!stack.isEmpty()) {
            String top = stack.remove(stack.size() - 1);
            System.out.println("Processed: " + top + " | Remaining: " + stack.size());
        }
    }
}

Terminal Output:

Processed: Step-3 | Remaining: 2
Processed: Step-2 | Remaining: 1
Processed: Step-1 | Remaining: 0

9. Common Developer Pitfalls & Traps 🔝

Wrong Order in Null Guard: list.isEmpty() || list == null

Writing if (list.isEmpty() || list == null) evaluates list.isEmpty() first and crashes with a NullPointerException when list is null! Always place list == null on the left side of || (or list != null on the left side of &&).

Expecting isEmpty() to Check for Blank Strings

An ArrayList<String> containing [""] (an empty string) has 1 element, so list.isEmpty() is false, even though list.get(0).isEmpty() is true.

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListIsEmptyFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        if (list.isEmpty() && (list.size() == 0)) {
            System.out.println("Check 1 Passed: New list isEmpty() is true.");
        }
        list.add("Item");
        if (!list.isEmpty()) {
            System.out.println("Check 2 Passed: Non-empty list returns false.");
        }
        list.clear();
        if (list.isEmpty()) {
            System.out.println("Check 3 Passed: Cleared list isEmpty() is true.");
        }
        System.out.println("All ArrayList.isEmpty() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: New list isEmpty() is true.
Check 2 Passed: Non-empty list returns false.
Check 3 Passed: Cleared list isEmpty() is true.
All ArrayList.isEmpty() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Why do code linters prefer list.isEmpty() over list.size() == 0?

list.isEmpty() expresses intent directly ("is the list empty?") and is guaranteed to be O(1) across almost all Java collections, whereas size() on certain concurrent collections (like ConcurrentLinkedQueue) takes O(n) time.

Is there a built-in isNotEmpty() method on ArrayList?

No. In standard Java, negate isEmpty() using the logical NOT operator: if (!list.isEmpty()).

Do I need to check !list.isEmpty() before a for-each loop?

No. If list.isEmpty() is true, a for (String s : list) loop simply executes zero iterations without any error. Only guard with !list.isEmpty() when you execute extra setup or header logic outside the loop.

Should my method return null or an empty ArrayList when no results are found?

Effective Java Item 54 recommends returning an empty list (such as Collections.emptyList() or an empty ArrayList) rather than null so callers never suffer a NullPointerException.

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