Java Collections的emptyList、EMPTY_LIST詳解與使用說明
Collections的emptyList、EMPTY_LIST使用
今天在看大佬寫的代碼的時候,結(jié)果集為空的情況,他返回的不是null,而是:
return Collections.EMPTY_LIST;
我們都知道返回null,很有可能造成空指針異常,可以使用emptyList或EMPTY_LIST就可以避免這個問題,除非你想捕獲這個為空的信息
我們在使用emptyList空的方法返回空集合的時候要注意,這個空集合是不可變的。
空的集合不可以使用add方法,會報UnsupportedOperationException異常,看如下源碼:
public void add(int index, E element) { throw new UnsupportedOperationException(); }
空集合對象不可以使用put方法,會報IndexOutOfBoundsException異常,看如下源碼:
public E get(int index) { throw new IndexOutOfBoundsException("Index: "+index); }
但是對于for循環(huán)都不會發(fā)生異常,如下的示例:
List<String> list1 = Collections.emptyList(); for(String s:list1) { } for(int i=0;i<list1.size();i++) { }
上面的兩種for循環(huán)都可以正常的執(zhí)行,第一種foreach循環(huán),實際編譯之后會變成迭代器的模式,這樣我們就好理解為什么可以正常執(zhí)行;第二種是只調(diào)用了size方法,我們可以看到源碼直接返回0;
public int size() {return 0;}
emptyList和EMPTY_LIST的區(qū)別,我們看下源碼:
/** * The empty list (immutable). This list is serializable. * * @see #emptyList() */ @SuppressWarnings("unchecked") public static final List EMPTY_LIST = new EmptyList<>();
/** * 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; }
我們看到EMPTY_LIST 是Collections類的一個靜態(tài)常量,而emptyList是支持泛型的。若是不需要泛型的地方可以直接使用 EMPTY_LIST ,若是需要泛型的地方就需要使用emptyList。
通過上面的分析我們可以很清楚的知道什么時候使用emptyList;Collections集合中還有其它的幾種空集合emptyMap、emptySet,他們的使用方法跟上面的大同小異。
Collections.emptyList()使用注意
偶然發(fā)現(xiàn)有小伙伴錯誤地使用了Collections.emptyList()方法,這里記錄一下。它的使用方式是:
public void run() { ...... List list = buildList(param); ...... Object newNode = getNode(...); list.add(newNode); ...... } public List buildList(Object param) { if (isInValid(param)) { return Collections.emptyList(); } else { ...... } }
buildList方法中可能會返回一個"空的List",后續(xù)還可能往這個List添加元素(或者移除元素),但是沒有注意Collections.emptyList方法返回的是一個EMPTY_LIST:
public static final <T> List<T> emptyList() { return (List<T>) EMPTY_LIST; }
它是一個static final修飾的成員變量,是一個EmptyList類的實例:
public static final List EMPTY_LIST = new EmptyList<>();
這個EmptyList是一個靜態(tài)內(nèi)部類,和ArrayList一樣繼承自AbstractList:
private static class EmptyList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 8842843931221139166L; public Iterator<E> iterator() { return emptyIterator(); } public ListIterator<E> listIterator() { return emptyListIterator(); } public int size() {return 0;} public boolean isEmpty() {return true;} public boolean contains(Object obj) {return false;} public boolean containsAll(Collection<?> c) { return c.isEmpty(); } public Object[] toArray() { return new Object[0]; } public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } public E get(int index) { throw new IndexOutOfBoundsException("Index: "+index); } public boolean equals(Object o) { return (o instanceof List) && ((List<?>)o).isEmpty(); } public int hashCode() { return 1; } // Preserves singleton property private Object readResolve() { return EMPTY_LIST; } }
可以看到這個EmptList沒有重寫add方法,并且get方法也是直接拋出一個IndexOutOfBoundsException異常。既然沒有重寫add方法,那么看看父類AbstractList中的add方法:
public boolean add(E e) { add(size(), e); return true; } public void add(int index, E element) { throw new UnsupportedOperationException(); }
可以看到直接拋出的UnsupportedOperationException異常。再回到EmptyList類中,它對外提供的一些方法也很明顯地限制了它的使用范圍。
對于Collections.emptyList(),或者說Collections.EMPTY_LIST,最好只把它當(dāng)做一個空列表的標(biāo)識(可以想象成一個frozen過的空List),不要對其做一些增刪改查的操作。如果程序中的一些分支邏輯返回了這種實例,測試的時候又沒有覆蓋到,在生產(chǎn)環(huán)境如果走到了這個分支邏輯,那就麻煩了~
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JAVA使用commos-fileupload實現(xiàn)文件上傳與下載實例解析
這篇文章主要介紹了JAVA使用commos-fileupload實現(xiàn)文件上傳與下載的相關(guān)資料,需要的朋友可以參考下2016-02-02利用spring?boot+WebSocket實現(xiàn)后臺主動消息推送功能
目前對于服務(wù)端向客戶端推送數(shù)據(jù),常用技術(shù)方案有輪詢、websocket等,下面這篇文章主要給大家介紹了關(guān)于利用spring?boot+WebSocket實現(xiàn)后臺主動消息推送功能的相關(guān)資料,需要的朋友可以參考下2022-04-04Java Callable接口實現(xiàn)細節(jié)詳解
這篇文章主要介紹了Java Callable接口實現(xiàn)細節(jié)詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05java.lang.ExceptionInInitializerError異常的解決方法
這篇文章主要為大家詳細介紹了java.lang.ExceptionInInitializerError異常的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10