久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Java中Collections.emptyList()的注意事項(xiàng)

瀏覽:48日期:2022-08-15 10:05:07

偶然發(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)識(shí)(可以想象成一個(gè)frozen過的空List),不要對其做一些增刪改查的操作。如果程序中的一些分支邏輯返回了這種實(shí)例,測試的時(shí)候又沒有覆蓋到,在生產(chǎn)環(huán)境如果走到了這個(gè)分支邏輯,那就麻煩了~

總結(jié)

到此這篇關(guān)于Java中Collections.emptyList()注意事項(xiàng)的文章就介紹到這了,更多相關(guān)Java Collections.emptyList()注意內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 榆社县| 青神县| 息烽县| 囊谦县| 保亭| 佛教| 林甸县| 石河子市| 固安县| 理塘县| 黄梅县| 永年县| 堆龙德庆县| 墨竹工卡县| 黔江区| 右玉县| 上饶县| 襄汾县| 乐平市| 甘德县| 应用必备| 云梦县| 安陆市| 阿勒泰市| 北辰区| 循化| 五莲县| 西充县| 华阴市| 临沧市| 宜良县| 都兰县| 马尔康县| 禄劝| 美姑县| 利津县| 平山县| 绵阳市| 鄂州市| 奈曼旗| 南溪县|