Collections是列表的工具类,其中有好多方便实用的方法。主要是对列表的查找、替换、排序、反转等操作。今天介绍一下emptyList()方法的使用,因为这个方法有一个大坑!
目录
-
- 1、emptyList()方法的使用
1、emptyList()方法的使用
- 通过()方法的相关源码可以得知它实际上就是返回了一个空的List,但是这个List和我们平时常用的那个List是不一样的。这个方法返回的List是Collections类的一个静态内部类,它继承AbstractList后并没有实现add()、remove()等方法,因此这个返回值List并不能增加删除元素。
- 既然这个List不能进行增删操作,那么它有何意义呢?
- 这个方法主要目的就是返回一个不可变的列表,使用这个方法作为返回值就不需要再创建一个新对象,可以减少内存开销。并且返回一个size为0的List,调用者不需要校验返回值是否为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 = ();
* </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;
}
}
- ()方法的测试
public class CollectionsTest {
public static void main(String[] a) {
List<Integer> list = new ArrayList<Integer>();
(1);
(2);
(list);
list = ();
(list);
(3);
}
}
//执行结果
[1, 2]
Exception in thread "main"
at (:131)
at (:91)[]
at (:22)