Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collections.emptyList()

Returns an empty unmodifiable list. See also emptyMap() and emptySet().

Available since: Java 5

Syntax

public static final <T> List<T> emptyList()

Return value

List<T>A shared empty list that cannot be modified.

Examples

A method returns an empty list instead of null — the caller needs no checks:

List<String> findTags(String post) {
    if (post.isBlank()) {
        return Collections.emptyList();
    }
    return List.of(post.split(" "));
}
 
void main() {
    IO.println(findTags(""));
    IO.println(findTags("java streams"));
    IO.println(findTags("").size());
}

Output:

[]
[java, streams]
0

You cannot add an element to such a list:

void main() {
    List<String> tags = Collections.emptyList();
    tags.add("java");
}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException

Notes

In modern code List.of() does the same; the difference is that emptyList().contains(null) returns false, while List.of().contains(null) throws NullPointerException. The method does not create a new object on each call. If you need to fill the list later, create new ArrayList<>().

See also

In the tutorial

  • Collection helper methods — The Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.

Thanks for reading!

Donate to the site — we work hard for you.