Java中Collections.emptyList()的注意事項(xiàng)
偶然發(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類中,它對(duì)外提供的一些方法也很明顯地限制了它的使用范圍。
對(duì)于Collections.emptyList(),或者說Collections.EMPTY_LIST,最好只把它當(dāng)做一個(gè)空列表的標(biāo)識(shí)(可以想象成一個(gè)frozen過的空List),不要對(duì)其做一些增刪改查的操作。如果程序中的一些分支邏輯返回了這種實(shí)例,測(cè)試的時(shí)候又沒有覆蓋到,在生產(chǎn)環(huán)境如果走到了這個(gè)分支邏輯,那就麻煩了~
總結(jié)
到此這篇關(guān)于Java中Collections.emptyList()注意事項(xiàng)的文章就介紹到這了,更多相關(guān)Java Collections.emptyList()注意內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 什么是python的自省2. php模擬實(shí)現(xiàn)斗地主發(fā)牌3. 詳解Android studio 動(dòng)態(tài)fragment的用法4. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼5. MyBatis中的JdbcType映射使用詳解6. vue 使用localstorage實(shí)現(xiàn)面包屑的操作7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Vuex localStorage的具體使用9. Python random庫使用方法及異常處理方案10. Docker 容器健康檢查機(jī)制

網(wǎng)公網(wǎng)安備