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

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

Returns an empty list (immutable). This list is serializable.

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

+69
java collections list
Feb 14 '13 at 8:43
source share
4 answers
  • Collections.EMPTY_LIST returns the old List style
  • Collections.emptyList() uses the output type and therefore returns a List<T>

Collections.emptyList () was added in Java 1.5 and is probably always preferable . This way you don't have to unnecessarily throw in your code.

Collections.emptyList() internally performs the cast for you.

 @SuppressWarnings("unchecked") public static final <T> List<T> emptyList() { return (List<T>) EMPTY_LIST; } 
+81
Feb 14 '13 at 8:44
source share

Allows you to 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; } 
+14
Feb 14 '13 at 8:45
source share

These 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 thing is that emptyList() returns a generic List<T> , so you can assign this list to a generic collection without any warning.

+9
Feb 14 '13 at 8:45
source share

In other words, EMPTY_LIST is not type safe:

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

Compared with:

  List<String> s = Collections.emptyList(); Set<Long> l = Collections.emptySet(); Map<Date, String> d = Collections.emptyMap(); 
+7
Mar 01 '13 at 7:08
source share



All Articles