Is Collections.emptyList() a drop-in replacement for Collections.EMPTY_LIST?

Viewed 411

Can I safely find and replace all Collections.EMPTY_LIST with Collections.emptyList(), or is there a chance of breaking things by doing this? Same question for Collections.EMPTY_SET and Collections.EMPTY_MAP.

The project I'm working on is using Java 8.

3 Answers

In principle yes, you can use the method wherever you used the constant, but bear in mind - the method is generic and won't raise a warning, whereas using the constant will raise a "raw type" warning in some Java versions (but not in Java 8, mind you). For completeness' sake, here's the code - notice the annotations used to eliminate the warnings:

@SuppressWarnings("rawtypes")
public static final List EMPTY_LIST = new EmptyList<>();

@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

If you look at the source code of Collections, you see that emptyList() is just a generic wrapper around EMPTY_LIST, so the answer is yes.

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

The implementations of emptyMap() and emptySet() are using the same structure.

Collections.EMPTY_LIST is an immutable list but not type-safe. Where as Collections.emptyList() is immutable and type-safe. Collections.emptyList() would be the preferred usage.

Related