原創:https://mingyang.blog.csdn.net/
在寫方法的時候可能結果集不存在,需要返回null,在調用這個方法的地方就要做一個null判斷,很繁瑣,容易出問題,這個時候就可以使用emptyList或EMPTY_LIST。但是也會有同學說我new ArrayList不就可以了,這樣是可以,但是每次我們new 一個集合對象的時候都會有一個初始化空間,占用內存資源,積少成多會浪費很多的資源,Collections中的空集合對象是一個靜態常量,在內存中只存在一份,所以能夠節省內存資源。
注意:
我們在使用emptyList空的方法返回空集合的時候要注意,這個空集合是不可變的。
空的集合不可以使用add方法,會報UnsupportedOperationException異常,看如下源碼:
public void add(int index, E element) { throw new UnsupportedOperationException(); }
空集合對象不可以使用put方法,會報IndexOutOfBoundsException異常,看如下源碼:
public E get(int index) { throw new IndexOutOfBoundsException("Index: "+index); }
但是對於for循環都不會發生異常,如下的示例:
List<String> list1 = Collections.emptyList(); for(String s:list1) { } for(int i=0;i<list1.size();i++) { }
上面的兩種for循環都可以正常的執行,第一種foreach循環,實際編譯之后會變成迭代器的模式,這樣我們就好理解為什么可以正常執行;第二種是只調用了size方法,我們可以看到源碼直接返回0;
public int size() {return 0;}
- 1
emptyList和EMPTY_LIST的區別,我們看下源碼:
/** * 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類的一個靜態常量,而emptyList是支持泛型的。若是不需要泛型的地方可以直接使用 EMPTY_LIST ,若是需要泛型的地方就需要使用emptyList。
通過上面的分析我們可以很清楚的知道什么時候使用emptyList;Collections集合中還有其它的幾種空集合emptyMap、emptySet,他們的使用方法跟上面的大同小異。
如果有用還請打個賞 ᕦ(・ㅂ・)ᕤ