Java Collections的emptyList、EMPTY_LIST詳解與使用說明
Collections的emptyList、EMPTY_LIST使用
今天在看大佬寫的代碼的時(shí)候,結(jié)果集為空的情況,他返回的不是null,而是:
return Collections.EMPTY_LIST;
我們都知道返回null,很有可能造成空指針異常,可以使用emptyList或EMPTY_LIST就可以避免這個(gè)問題,除非你想捕獲這個(gè)為空的信息
我們在使用emptyList空的方法返回空集合的時(shí)候要注意,這個(gè)空集合是不可變的。
空的集合不可以使用add方法,會(huì)報(bào)UnsupportedOperationException異常,看如下源碼:
public void add(int index, E element) { throw new UnsupportedOperationException(); }
空集合對象不可以使用put方法,會(huì)報(bào)IndexOutOfBoundsException異常,看如下源碼:
public E get(int index) { throw new IndexOutOfBoundsException("Index: "+index); }
但是對于for循環(huán)都不會(huì)發(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),實(shí)際編譯之后會(huì)變成迭代器的模式,這樣我們就好理解為什么可以正常執(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類的一個(gè)靜態(tài)常量,而emptyList是支持泛型的。若是不需要泛型的地方可以直接使用 EMPTY_LIST ,若是需要泛型的地方就需要使用emptyList。
通過上面的分析我們可以很清楚的知道什么時(shí)候使用emptyList;Collections集合中還有其它的幾種空集合emptyMap、emptySet,他們的使用方法跟上面的大同小異。
Collections.emptyList()使用注意
偶然發(fā)現(xiàn)有小伙伴錯(cuò)誤地使用了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方法中可能會(huì)返回一個(gè)"空的List",后續(xù)還可能往這個(gè)List添加元素(或者移除元素),但是沒有注意Collections.emptyList方法返回的是一個(gè)EMPTY_LIST:
public static final <T> List<T> emptyList() { return (List<T>) EMPTY_LIST; }
它是一個(gè)static final修飾的成員變量,是一個(gè)EmptyList類的實(shí)例:
public static final List EMPTY_LIST = new EmptyList<>();
這個(gè)EmptyList是一個(gè)靜態(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; } }
可以看到這個(gè)EmptList沒有重寫add方法,并且get方法也是直接拋出一個(gè)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)做一個(gè)空列表的標(biāo)識(可以想象成一個(gè)frozen過的空List),不要對其做一些增刪改查的操作。如果程序中的一些分支邏輯返回了這種實(shí)例,測試的時(shí)候又沒有覆蓋到,在生產(chǎn)環(huán)境如果走到了這個(gè)分支邏輯,那就麻煩了~
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載實(shí)例解析
這篇文章主要介紹了JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載的相關(guān)資料,需要的朋友可以參考下2016-02-02利用spring?boot+WebSocket實(shí)現(xiàn)后臺主動(dòng)消息推送功能
目前對于服務(wù)端向客戶端推送數(shù)據(jù),常用技術(shù)方案有輪詢、websocket等,下面這篇文章主要給大家介紹了關(guān)于利用spring?boot+WebSocket實(shí)現(xiàn)后臺主動(dòng)消息推送功能的相關(guān)資料,需要的朋友可以參考下2022-04-04Java Callable接口實(shí)現(xiàn)細(xì)節(jié)詳解
這篇文章主要介紹了Java Callable接口實(shí)現(xiàn)細(xì)節(jié)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05Java工具類實(shí)現(xiàn)高效編寫報(bào)表
對于報(bào)表數(shù)據(jù)大部分情況下使用寫sql的方式為大屏/報(bào)表提供數(shù)據(jù)來源,但是對于某些復(fù)雜情況下僅僅使用sql無法實(shí)現(xiàn),這篇文章主要介紹了Java工具類實(shí)現(xiàn)高效編寫報(bào)表2022-11-11java.lang.ExceptionInInitializerError異常的解決方法
這篇文章主要為大家詳細(xì)介紹了java.lang.ExceptionInInitializerError異常的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10