Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.isEmpty()

Checks whether a list is empty.

Available since: Java 1.2

Syntax

boolean isEmpty()

Return value

boolean`true` if the list has no elements.

Examples

A check before reading the first element:

void main() {
    List<String> orders = new ArrayList<>();
    if (orders.isEmpty()) {
        IO.println("No orders yet");
    }
    orders.add("#101");
    IO.println(orders.isEmpty());
}

Output:

No orders yet
false

Notes

list.isEmpty() reads better than list.size() == 0 and does the same. The method exists on all collections, on Map and on strings. If the variable itself is null, the call throws NullPointerException.

See also

  • List.size() — Returns the number of elements in a list.
  • List.getFirst() — Returns the first or the last element of an ordered collection.

In the tutorial

  • Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.

Thanks for reading!

Donate to the site — we work hard for you.