Collections.EMPTY_LIST和Collections.emptyList()简单使用体会

1.背景
在某些情况下,我们经常需要发挥一个空的集合对象,比如说在数据查询时,并不需要发挥一个NULL或是异常,那么就可以返回一个空的集合对象。
JDK提供了两个方式来返回集合对象,那么两者有何区别呢?那就看代码吧!

2.源码解析
EMPTY_LIST 是Collections定义的一个静态属性,是一个类变量,可以直接返回使用
public static final List EMPTY_LIST = new EmptyList();

这个是emptyList的代码
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}

从上面我们可以看出,emptyList不过是对EMPTY_LIST做了一个泛型支持。这点上我们就可以很清晰的了解两者不同的使用场景了!若是不需要泛型的情况,可以直接使用Collections,反之则使用emptyList().

3.使用
对于EMPTY_LIST就不多介绍了,我们可以直接使用Collections.EMPTY_LIST。
对于Collections.emptyList()的使用有点需要注意的地方。
若是定义了一个变量来保存这个空集合的话,那么没有问题。List<Person> emptyPersonList = Collections.emptyList();编译器会自动转化。
若是在某个场景下需要将空对象进行赋值那么就需要如下写法 organization.setPersonList(Collections.<Person> emptyList());

4.BTW
虽然在源码中存在
public int size() {return 0;}

public Object get(int index) {
throw new IndexOutOfBoundsException(“Index: “+index);
}
但是对于我们无论是
for (int i =0 ; i < …)还是 for (Person p : personList)都不会调用到get(int index)这个方法,可以放心使用!前一种方式我们可以很好理解,因为首先是调用了size().后者foreach的实现原理还需要考究下!

 

发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>