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)文章
java對象list使用stream根據(jù)某一個屬性轉(zhuǎn)換成map的3種方式舉例
開發(fā)小伙伴們通常會需要使用到對象和Map互相轉(zhuǎn)換的開發(fā)場景,下面這篇文章主要給大家介紹了關(guān)于java對象list使用stream根據(jù)某一個屬性轉(zhuǎn)換成map的3種方式,需要的朋友可以參考下2024-01-01Spring?Boot常用的參數(shù)驗證技巧和使用方法
Spring Boot是一個使用Java編寫的開源框架,用于快速構(gòu)建基于Spring的應(yīng)用程序,這篇文章主要介紹了Spring?Boot常用的參數(shù)驗證技巧和使用方法,需要的朋友可以參考下2023-09-09java枚舉enum,根據(jù)value值獲取key鍵的操作
這篇文章主要介紹了java枚舉enum,根據(jù)value值獲取key鍵的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02SpringBoot2.x中management.security.enabled=false無效的解決
這篇文章主要介紹了SpringBoot2.x中management.security.enabled=false無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07SpringBoot集成Beetl后統(tǒng)一處理頁面異常的方法
這篇文章主要介紹了SpringBoot集成Beetl后統(tǒng)一處理頁面異常的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08