亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java Collections.EMPTY_LIST與Collections.emptyList()的區(qū)別

 更新時間:2021年11月16日 15:31:44   作者:范亞明  
這篇文章主要介紹了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)文章

最新評論