java.util.Collections類—emptyList()方法的使用
Collections是列表的工具類,其中有好多方便實用的方法。主要是對列表的查找、替換、排序、反轉等操作。今天介紹一下emptyList()方法的使用,因為這個方法有一個大坑!
emptyList()方法的使用
通過java.util.Collections.emptyList()方法的相關源碼可以得知它實際上就是返回了一個空的List,但是這個List和我們平時常用的那個List是不一樣的。這個方法返回的List是Collections類的一個靜態(tài)內(nèi)部類,它繼承AbstractList后并沒有實現(xiàn)add()、remove()等方法,因此這個返回值List并不能增加刪除元素。
既然這個List不能進行增刪操作,那么它有何意義呢?
這個方法主要目的就是返回一個不可變的列表,使用這個方法作為返回值就不需要再創(chuàng)建一個新對象,可以減少內(nèi)存開銷。并且返回一個size為0的List,調(diào)用者不需要校驗返回值是否為null,所以建議使用這個方法返回可能為空的List。
emptySet()、emptyMap()方法同理。
/**
* The empty list (immutable). This list is serializable.
*
* @see #emptyList()
*/
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
*/
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
/**
* @serial include
*/
private static class EmptyList extends AbstractList<Object> implements RandomAccess,Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 8842843931221139166L;
public int size() {return 0;}
public boolean contains(Object obj) {return false;}
public Object get(int index) {
throw new IndexOutOfBoundsException("Index: "+index);
}
// Preserves singleton property
private Object readResolve() {
return EMPTY_LIST;
}
}
java.util.Collections.emptyList()方法的測試
public class CollectionsTest {
public static void main(String[] a) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
System.out.println(list);
list = Collections.emptyList();
System.out.println(list);
list.add(3);
}
}
//執(zhí)行結果
[1, 2]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:91)[]
at com.jiuqi.pay.importfile.test.CollectionsTest.main(CollectionsTest.java:22)
Java Collections.emptyList()方法的注意事項
emptyList()
作用:返回一個空的List(使用前提是不會再對返回的list進行增加和刪除操作);
好處:
1. new ArrayList()創(chuàng)建時有初始大小,占用內(nèi)存,emptyList()不用創(chuàng)建一個新的對象,可以減少內(nèi)存開銷;
2. 方法返回一個emptyList()時,不會報空指針異常,如果直接返回Null,沒有進行非空判斷就會報空指針異常;
注意:此List與常用的List不同,它是Collections類里的靜態(tài)內(nèi)部類,在繼承AbstractList后并沒有實現(xiàn)add()、remove()等方法,所以返回的List不能進行增加和刪除元素操作。
示例:
@Test
public void test1() {
String str = "";
List<String> list = getList(str);
System.out.println(list.size());
}
private static List<String> getList(String str) {
if (StringUtils.isBlank(str)) {
// 使用時不會報空指針
return Collections.emptyList();
// 使用null報空指針異常
// return null;
}
List<String> list = new ArrayList<String>();
list.add(str);
return list;
}
增刪操作:
@Test
public void test2() {
String str = "abc";
List<String> list = Collections.emptyList();
list.add(str);
System.out.println(list.size());
}
結果:

如果需要對collections.emptyList()進行增刪操作的話,就需要將collections.emptyList()轉換成ArrayList()進行操作。
示例:
@Test
public void test2() {
String str = "abc";
List<String> list = Collections.emptyList();
List<String> resultList = new ArrayList<>(list);
resultList.add(str);
System.out.println(resultList.size());
System.out.println(resultList);
}
結果:

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 淺談Java中Collections.sort對List排序的兩種方法
- Java使用Collections.sort()排序的方法
- java安全之CommonsCollections4詳解
- Java中的Collections類的使用示例詳解
- Java中Collections.sort的使用
- Java的可變參數(shù)與Collections類的功能示例解析
- Java中Collection與Collections的區(qū)別詳解
- Java Collection和Collections的區(qū)別
- Java中的集合工具類Collections詳解
- Java中Collections.sort()排序方法舉例詳解
- Java中Collection和Collections的區(qū)別
相關文章
安卓系統(tǒng)中實現(xiàn)搖一搖畫面振動效果的方法
這篇文章主要介紹了安卓系統(tǒng)中實現(xiàn)搖一搖畫面振動效果的方法,調(diào)用Android SDK中的SensorEventListener接口,需要的朋友可以參考下2015-07-07
Java object wait notify notifyAll代碼解析
這篇文章主要介紹了Java object wait notify notifyAll代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-11-11
理解Java注解及Spring的@Autowired是如何實現(xiàn)的
今天通過本文帶領大家學習注解的基礎知識,學習Spring的@Autowired是怎么實現(xiàn)的,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-07-07
使用maven實現(xiàn)redis與idea的連接問題
這篇文章主要介紹了使用maven實現(xiàn)redis與idea的連接問題,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-07-07
SpringCloud?Feign使用ApacheHttpClient代替默認client方式
這篇文章主要介紹了SpringCloud?Feign使用ApacheHttpClient代替默認client方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot使用classfinal-maven-plugin插件加密Jar包的示例代碼
這篇文章給大家介紹了SpringBoot使用classfinal-maven-plugin插件加密Jar包的實例,文中通過代碼示例和圖文講解的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2024-02-02
解析Java的InputStream類并借助其讀取ppt文件
這篇文章主要介紹了Java的InputStream類并借助其讀取ppt文件,講到了InputStream類中一些常用的方法的問題,需要的朋友可以參考下2015-11-11

