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添加元素(或者移除元素),但是沒(méi)有注意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沒(méi)有重寫add方法,并且get方法也是直接拋出一個(gè)IndexOutOfBoundsException異常。既然沒(méi)有重寫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(),或者說(shuō)Collections.EMPTY_LIST,最好只把它當(dāng)做一個(gè)空列表的標(biāo)識(shí)(可以想象成一個(gè)frozen過(guò)的空List),不要對(duì)其做一些增刪改查的操作。如果程序中的一些分支邏輯返回了這種實(shí)例,測(cè)試的時(shí)候又沒(méi)有覆蓋到,在生產(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. 使用.net core 自帶DI框架實(shí)現(xiàn)延遲加載功能2. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究3. Angular獲取ngIf渲染的Dom元素示例4. php面向?qū)ο蟪绦蛟O(shè)計(jì)介紹5. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp6. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)7. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介8. php測(cè)試程序運(yùn)行速度和頁(yè)面執(zhí)行速度的代碼9. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問(wèn)題分析10. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析
