What is the difference between Collections.emptyList() and Collections.EMPTY_LIST

JavaListCollections

Java Problem Overview


In Java, we have Collections.emptyList() and Collections.EMPTY_LIST. Both have the same property:

> Returns the empty list (immutable). This list is serializable.

So what is the exact difference between using the one or the other?

Java Solutions


Solution 1 - Java

  • Collections.EMPTY_LIST returns an old-style List
  • Collections.emptyList() uses type-inference and therefore returns List<T>

Collections.emptyList() was added in Java 1.5 and it is probably always preferable. This way, you don't need to unnecessarily cast around within your code.

Collections.emptyList() intrinsically does the cast for you.

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

Solution 2 - Java

Lets get to the source :

 public static final List EMPTY_LIST = new EmptyList<>();

and

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

Solution 3 - Java

In other words, EMPTY_LIST is not type safe:

  List list = Collections.EMPTY_LIST;
  Set set = Collections.EMPTY_SET;
  Map map = Collections.EMPTY_MAP;

As compared to:

    List<String> s = Collections.emptyList();
    Set<Long> l = Collections.emptySet();
    Map<Date, String> d = Collections.emptyMap();

Solution 4 - Java

They are absolutely equal objects.

public static final List EMPTY_LIST = new EmptyList<>();

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

The only one is that emptyList() returns generic List<T>, so you can assign this list to generic collection without any warnings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpoitroaeView Question on Stackoverflow
Solution 1 - JavapoitroaeView Answer on Stackoverflow
Solution 2 - JavaNimChimpskyView Answer on Stackoverflow
Solution 3 - Javamel3kingsView Answer on Stackoverflow
Solution 4 - JavaAndremoniyView Answer on Stackoverflow