Collections.EMPTY_LIST返回的是一个空的List。为什么需要空的List呢?有时候我们在函数中需要返回一个List,但是这个List是空的,如果我们直接返回null的话,调用者还需要进行null的判断,所以一般建议返回一个空的List。(编者注:比如,用到list.size(),这个时候会忘记也很麻烦,再判断是否为空。不像循环,肯定会判断是否为空 。所以不要return null,return Collections.EMPTY_LIST这个比较好。EMPTY_LIST的size为0)Collections.EMPTY_LIST返回的这个空的List是不能进行添加元素这类操作的。这时候你有可能会说,我直接返回一个new ArrayList()呗,但是new ArrayList()在初始化时会占用一定的资源,所以在这种场景下,还是建议返回Collections.EMPTY_LIST。
Collections. emptyList()返回的也是一个空的List,它与Collections.EMPTY_LIST的唯一区别是,Collections. emptyList()支持泛型,所以在需要泛型的时候,可以使用Collections. emptyList()。
Collections.EMPTY_MAP和Collections.EMPTY_SET同理。
Collections.EMPTY_LIST的实现代码:
- /**
- * The empty list (immutable). This list is serializable.
- *
- * @see #emptyList()
- */
- @SuppressWarnings("unchecked")
- public static final List EMPTY_LIST = new EmptyList<>();
Collections. emptyList()的实现代码:
- /**
- * Returns the empty list (immutable). This list is serializable.
- *
- * <p>This example illustrates the type-safe way to obtain an empty list:
- * <pre>
- * List<String> s = Collections.emptyList();
- * </pre>
- * Implementation note: Implementations of this method need not
- * create a separate <tt>List</tt> object for each call. Using this
- * method is likely to have comparable cost to using the like-named
- * field. (Unlike this method, the field does not provide type safety.)
- *
- * @see #EMPTY_LIST
- * @since 1.5
- */
- @SuppressWarnings("unchecked")
- public static final <T> List<T> emptyList() {
- return (List<T>) EMPTY_LIST;
- }
测试代码演示:
- import java.util.Collections;
- import java.util.List;
- public class CollectionsTest {
- public static void main(String[] args) {
- List list1 = Collections.EMPTY_LIST;
- System.out.println(list1.size());
- try {
- list1.add(1);
- } catch (Exception e) {
- e.printStackTrace();
- }
- List<Integer> list2 = Collections.<Integer>emptyList();
- System.out.println(list2.size());
- try {
- list2.add(1);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
测试输出:
REFS:http://blog.csdn.net/liyuming0000/article/details/49474659