Collections.emptyList() vs. New List Instance – Collections.emptyList() vs. New List Instance

最后修改: 2018年 8月 11日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this short tutorial, we’ll illustrate the difference between Collections.emptyList() and a new list instance.

在这个简短的教程中,我们将说明Collections.emptyList()和一个新的列表实例之间的区别。

2. Immutability

2.不变性

The core difference between java.util.Collections.emptyList() and a new list e.g. new ArrayList<>() is immutability.

java.util.Collections.emptyList()和一个新的列表,例如new ArrayList<>()之间的核心区别是不可改变性。

Collections.emptyList() returns a list (java.util.Collections.EmptyList) that can’t be modified.

Collections.emptyList()返回一个不能被修改的列表(java.util.Collections.EmptyList)。

When creating a new list instance you can modify it depending on the implementation:

当创建一个新的列表实例时,你可以根据实现情况来修改它。

@Test
public void givenArrayList_whenAddingElement_addsNewElement() {	 	 
    List<String> mutableList = new ArrayList<>();	 	 
    mutableList.add("test");	 	 
 
    assertEquals(mutableList.size(), 1);	 	 
    assertEquals(mutableList.get(0), "test");	 	 
}
	 	 
@Test(expected = UnsupportedOperationException.class)	 	 
public void givenCollectionsEmptyList_whenAdding_throwsException() {	 	 
    List<String> immutableList = Collections.emptyList();	 	 
    immutableList.add("test");	 	 
}

3. Object Creation

3.对象创建

Collection.emptyList() creates a new empty list instance only once, as shown in source code:

Collection.emptyList()只创建一次新的空列表实例,如源代码所示。

public static final List EMPTY_LIST = new EmptyList<>();

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

4. Readability

4.可读性

When you want to explicitly create an empty list, then Collections.emptyList() expressed the original intention better e.g. new ArrayList<>().

当你想明确地创建一个空列表时,那么Collections.emptyList()更好地表达了原意,例如new ArrayList<>()

5. Conclusion

5.总结

In this to the point article, we’ve focused on the differences between the Collections.emptyList() and a new list instance.

在这篇开门见山的文章中,我们着重介绍了Collections.emptyList()和一个新的列表实例之间的区别。

As always full source code is available over on GitHub.

像往常一样,完整的源代码可在GitHub上获得