Java Collections的emptyList、EMPTY_LIST詳解與使用說明
Collections的emptyList、EMPTY_LIST使用
今天在看大佬寫的代碼的時(shí)候,結(jié)果集為空的情況,他返回的不是null,而是:
return Collections.EMPTY_LIST;
我們都知道返回null,很有可能造成空指針異常,可以使用emptyList或EMPTY_LIST就可以避免這個(gè)問題,除非你想捕獲這個(gè)為空的信息
我們?cè)谑褂胑mptyList空的方法返回空集合的時(shí)候要注意,這個(gè)空集合是不可變的。
空的集合不可以使用add方法,會(huì)報(bào)UnsupportedOperationException異常,看如下源碼:
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
空集合對(duì)象不可以使用put方法,會(huì)報(bào)IndexOutOfBoundsException異常,看如下源碼:
public E get(int index) {
throw new IndexOutOfBoundsException("Index: "+index);
}
但是對(duì)于for循環(huán)都不會(huì)發(fā)生異常,如下的示例:
List<String> list1 = Collections.emptyList();
for(String s:list1) {
}
for(int i=0;i<list1.size();i++) {
}
上面的兩種for循環(huán)都可以正常的執(zhí)行,第一種foreach循環(huán),實(shí)際編譯之后會(huì)變成迭代器的模式,這樣我們就好理解為什么可以正常執(zhí)行;第二種是只調(diào)用了size方法,我們可以看到源碼直接返回0;
public int size() {return 0;}
emptyList和EMPTY_LIST的區(qū)別,我們看下源碼:
/**
* The empty list (immutable). This list is serializable.
*
* @see #emptyList()
*/
@SuppressWarnings("unchecked")
public static final List EMPTY_LIST = new EmptyList<>();
/**
* Returns the empty list (immutable). This list is serializable.
*
* <p>This example illustrates the type-safe way to obtain an empty list:
* <pre>
* List<String> s = Collections.emptyList();
* </pre>
* Implementation note: Implementations of this method need not
* create a separate <tt>List</tt> object for each call. Using this
* method is likely to have comparable cost to using the like-named
* field. (Unlike this method, the field does not provide type safety.)
*
* @see #EMPTY_LIST
* @since 1.5
*/
@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
我們看到EMPTY_LIST 是Collections類的一個(gè)靜態(tài)常量,而emptyList是支持泛型的。若是不需要泛型的地方可以直接使用 EMPTY_LIST ,若是需要泛型的地方就需要使用emptyList。
通過上面的分析我們可以很清楚的知道什么時(shí)候使用emptyList;Collections集合中還有其它的幾種空集合emptyMap、emptySet,他們的使用方法跟上面的大同小異。
Collections.emptyList()使用注意
偶然發(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è)分支邏輯,那就麻煩了~
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
3分鐘純 Java 注解搭個(gè)管理系統(tǒng)的示例代碼
這篇文章主要介紹了3分鐘純 Java 注解搭個(gè)管理系統(tǒng)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
SpringAOP中基于注解實(shí)現(xiàn)通用日志打印方法詳解
這篇文章主要介紹了SpringAOP中基于注解實(shí)現(xiàn)通用日志打印方法詳解,在日常開發(fā)中,項(xiàng)目里日志是必不可少的,一般有業(yè)務(wù)日志,數(shù)據(jù)庫日志,異常日志等,主要用于幫助程序猿后期排查一些生產(chǎn)中的bug,需要的朋友可以參考下2023-12-12
java微信掃描公眾號(hào)二維碼實(shí)現(xiàn)登陸功能
這篇文章主要為大家詳細(xì)介紹了PHP微信掃描公眾號(hào)二維碼實(shí)現(xiàn)登陸功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
一篇文章帶你搞定 springsecurity基于數(shù)據(jù)庫的認(rèn)證(springsecurity整合mybatis)
這篇文章主要介紹了一篇文章帶你搞定 springsecurity基于數(shù)據(jù)庫的認(rèn)證(springsecurity整合mybatis),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
ssm框架下web項(xiàng)目,web.xml配置文件的作用(詳解)
下面小編就為大家?guī)硪黄猻sm框架下web項(xiàng)目,web.xml配置文件的作用(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
尋找二叉樹最遠(yuǎn)的葉子結(jié)點(diǎn)(實(shí)例講解)
下面小編就為大家分享一篇尋找二叉樹最遠(yuǎn)的葉子結(jié)點(diǎn)的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12
Java經(jīng)典設(shè)計(jì)模式之策略模式原理與用法詳解
這篇文章主要介紹了Java經(jīng)典設(shè)計(jì)模式之策略模式,簡(jiǎn)單說明了策略模式的概念、原理并結(jié)合實(shí)例形式分析了java策略模式的具有用法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-08-08

