Monday, January 4, 2016

Java Programming: Collections.emptyList() vs Collections.EMPTY_LIST


In Java, we both have Collections.emptyList() and Collections.EMPTY_LIST but many are confused about the difference of these two.

Collections.EMPTY_LIST returns a non type safe List, which means that you can add any type of objects to it.


List list = Collections.EMPTY_LIST;

Collections.emptyList() was introduced in Java 1.5 and returns a type safe List<T>. You can assign this list to a generic collection so you wouldn’t get the “unchecked” compiler warning. The compiler will automatically detect the type parameter of the generic method based on the target type. 

List<String> list = Collections.emptyList();

Take note though that both Collections.emptyList() and Collections.EMPTY_LIST return an immutable list (e.g. you cannot modify the list by adding, updating or deleting items). So if you want to return an empty list that you can still modify later on, then don’t use those two, instead use this approach:


List<String> list = new ArrayList<String>();

The downside of this approach is that new ArrayList<T>() will always create a new instance (extra memory consumption) while Collections.emptyList() and Collections.EMPTY_LIST will return the same static instance each time it is called.

Aside from the list collection, set and map also have the equivalent approach for setting an empty instance. 


Set set = Collections.EMPTY_SET;
Set<String> set = Collections.emptySet();
Map map = Collections.EMPTY_MAP;
Map<String, Integer> map = Collections.emptyMap();

No comments:

Post a Comment