Java中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)境如果走到了這個分支邏輯,那就麻煩了~
總結(jié)
到此這篇關(guān)于Java中Collections.emptyList()注意事項的文章就介紹到這了,更多相關(guān)Java Collections.emptyList()注意內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. IntelliJ IDEA導(dǎo)入jar包的方法2. SSM框架JSP使用Layui實現(xiàn)layer彈出層效果3. 刪除docker里建立容器的操作方法4. IntelliJ IDEA導(dǎo)出項目的方法5. .Net中的Http請求調(diào)用詳解(Post與Get)6. 如果你恨一個程序員,忽悠他去做iOS開發(fā)7. JS如何在數(shù)組指定位置插入元素8. IDEA調(diào)試源碼小技巧之辨別抽象類或接口多種實現(xiàn)類的正確路徑9. java使用xfire搭建webservice服務(wù)的過程詳解10. Java源碼解析之ClassLoader
