Android 开发

Collections 的 emptyList()、emptyM

2018-12-04  本文已影响6人  BugFree张瑞
集合api

参考链接:

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

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

注意:返回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;

}


上一篇 下一篇

猜你喜欢

热点阅读