Collections 的 emptyList()、emptyMap() 、emptySet()

《Collections 的 emptyList()、emptyMap() 、emptySet()》 集合api

参考链接:

https://stackoverflow.com/questions/14846920/collections-emptymap-vs-new-hashmap

会生成指定类型的空 List Set Map,而且是不可变的,如进行 add() 操作会报 java.lang.UnsupportedOperationException,返回这样不可变的空集合有什么作用呢?

  • 方法内部会返回 static final 成员,创建后相当于常量可重复引用,当需要使用一个空集合时不用 new 去分配内存,比如一个测试用例 API 接口就需要一个 Map<String,Object> ,若此时只需要一个空 map 跑用例,直接用 Collections.emptyMap() 作为参数即可
  • 防止空指针出现,当你的代码需要一个集合而这个集合可能不存在,此时尽量使用空集合而不是 null,因为集合一个常用的操作就是遍历,你不知道你返回的结果在后续会不会被遍历。比如一个查询步骤返回一个集合,当返回一个空集合是就可以用这类方法,还可以防止后续对这个空集合再做 add 操作。

注意:返回0长度的数组或者集合,而不是 null

而且当我们每次都 new ArrayList() 或者 new LinkedList() ,在创建的时候就会有初始大小,多少会占用一些内存。每次使用都 new 一个空的 list 集合,浪费就积少成多,浪费就严重啦。

/**
* The empty map (immutable).  This map is serializable.
*
* @see #emptyMap()
* @since 1.3
*/
@SuppressWarnings("rawtypes")

public static final Map EMPTY_MAP =  new EmptyMap<>();

/**

* Returns an empty map (immutable).  This map is serializable.

*
* <p>This example illustrates the type-safe way to obtain an empty map:

* @implNote Implementations of this method need not create a separate

* {@code Map} 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.)

*

* @param <K> the class of the map keys

* @param <V> the class of the map values

* @return an empty map

* @see #EMPTY_MAP

* @since 1.5

*/
@SuppressWarnings("unchecked")

public static final <K,V> Map<K,V> emptyMap() {

return (Map<K,V>) EMPTY_MAP;

}


    原文作者:BugFree张瑞
    原文地址: https://www.jianshu.com/p/e252d50abce3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞