Java Collections.EMPTY_LIST與Collections.emptyList()的區(qū)別
Collections.EMPTY_LIST與Collections.emptyList()的區(qū)別
Collections.EMPTY_LIST返回的是一個空的List。為什么需要空的List呢?有時候我們在函數(shù)中需要返回一個List,但是這個List是空的,如果我們直接返回null的話,調(diào)用者還需要進行null的判斷,所以一般建議返回一個空的List。
Collections.EMPTY_LIST返回的這個空的List是不能進行添加元素這類操作的。這時候你有可能會說,我直接返回一個new ArrayList()唄,但是new ArrayList()在初始化時會占用一定的資源,所以在這種場景下,還是建議返回Collections.EMPTY_LIST。
Collections. emptyList()返回的也是一個空的List,它與Collections.EMPTY_LIST的唯一區(qū)別是,Collections. emptyList()支持泛型,所以在需要泛型的時候,可以使用Collections. emptyList()。
Collections.EMPTY_MAP和Collections.EMPTY_SET同理。
Collections.EMPTY_LIST的實現(xiàn)代碼
/**
* The empty list (immutable). This list is serializable.
*
* @see #emptyList()
*/
@SuppressWarnings("unchecked")
public static final List EMPTY_LIST = new EmptyList<>();
Collections. emptyList()的實現(xiàn)代碼
/**
* 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;
}
使用Collections.emptyMap()引起的一個奇怪的問題
以下是控制臺信息

第二行是很不起眼的一條異常信息,不知為何沒有把整個錯誤堆棧輸出。
一開始沒有注意到這條異常信息,于是設(shè)斷點,調(diào)試,結(jié)果每次執(zhí)行幾句就莫名其妙地轉(zhuǎn)入ThreadPoolExecutor中執(zhí)行。
最后注意到上面的異常信息后,發(fā)現(xiàn)對一個類型為Map的成員變量初始化有問題:
protected Map<String, String> optionalStrParams = Collections.emptyMap();
如此修改:
protected Map<String, String> optionalStrParams = new HashMap<String, String>();
我的本意是初始化為一個空的Map,EmptyMap在此場景下不合適。
EmptyMap的背景
在某些情況下,我們經(jīng)常需要發(fā)揮一個空的集合對象,比如說在數(shù)據(jù)查詢時,并不需要發(fā)揮一個NULL或是異常,那么就可以返回一個空的集合對象。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于ThreadLocal和InheritableThreadLocal解析
這篇文章主要介紹了關(guān)于ThreadLocal和InheritableThreadLocal解析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03
java中實現(xiàn)map與對象相互轉(zhuǎn)換的幾種實現(xiàn)
這篇文章主要介紹了java中實現(xiàn)map與對象相互轉(zhuǎn)換的幾種實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07
基于logback 實現(xiàn)springboot超級詳細的日志配置
java web 下有好幾種日志框架,比如:logback,log4j,log4j2(slj4f 并不是一種日志框架,它相當于定義了規(guī)范,實現(xiàn)了這個規(guī)范的日志框架就能夠用 slj4f 調(diào)用)。這篇文章主要介紹了基于logback springboot超級詳細的日志配置,需要的朋友可以參考下2019-06-06
Java使用字節(jié)流實現(xiàn)圖片音頻的復(fù)制
今天帶大家學習Java的相關(guān)知識,文章圍繞著Java如何使用字節(jié)流實現(xiàn)圖片音頻的復(fù)制展開,文中有非常詳細的介紹,需要的朋友可以參考下2021-06-06

