Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collection.isEmpty() — check whether a collection is empty

`Collection.isEmpty()` returns `true` when a collection has no elements and `false` otherwise. It does not change the collection.

Version: Java SE 21

Syntax

boolean isEmpty()

In Java SE 21, Collection.isEmpty() is a no-argument instance method declared by the java.util.Collection<E> interface. Call it on a collection object, as in items.isEmpty(). It returns a boolean: true for zero elements and false for one or more.

The call does not modify the collection. If you only need to know whether it is empty, prefer items.isEmpty() to items.size() == 0: the two expressions give the same answer, but the first states your intent directly. To check for a nonempty collection, use !items.isEmpty().

An empty collection is an object with no elements, not a null reference. If items is null, items.isEmpty() throws NullPointerException. If the collection permits null elements, as ArrayList does, a stored null still counts as an element.

Examples

import java.util.ArrayList;
import java.util.Collection;

public class Main {
    public static void main(String[] args) {
        Collection<String> items = new ArrayList<>();
        System.out.println(items.isEmpty());

        items.add(null);
        System.out.println(items.isEmpty());

        items.clear();
        System.out.println(items.isEmpty());
    }
}

Result

true
false
true

The new `ArrayList` is empty, so the result is `true`. After adding `null`, it has one element, so the result is `false`. After `clear()`, it has no elements again and the result is `true`.

Related lessons

  • Java · Lesson 60 · Basic · Version: 2
  • Java · Lesson 61 · Basic · Version: 2

Sources