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. vue3+ts+elementPLus實(shí)現(xiàn)v-preview指令2. Xml簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理3. 使用Hangfire+.NET 6實(shí)現(xiàn)定時(shí)任務(wù)管理(推薦)4. 如何在jsp界面中插入圖片5. phpstudy apache開啟ssi使用詳解6. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器7. jsp文件下載功能實(shí)現(xiàn)代碼8. 詳解瀏覽器的緩存機(jī)制9. 爬取今日頭條Ajax請(qǐng)求10. xml中的空格之完全解說
