Collections.EMPTY_LIST和Collections.emptyList()简单使用心得
来源:互联网 发布:帝国cms 淘客 编辑:程序博客网 时间:2024/06/08 05:15
1.背景
在某些情况下,我们经常需要发挥一个空的集合对象,比如说在数据查询时,并不需要发挥一个NULL或是异常,那么就可以返回一个空的集合对象。
JDK提供了两个方式来返回集合对象,那么两者有何区别呢?那就看代码吧!
2.源码解析
从上面我们可以看出,emptyList不过是对EMPTY_LIST做了一个泛型支持。这点上我们就可以很清晰的了解两者不同的使用场景了!若是不需要泛型的情况,可以直接使用Collections,反之则使用emptyList().
3.使用
对于EMPTY_LIST就不多介绍了,我们可以直接使用Collections.EMPTY_LIST。
对于Collections.emptyList()的使用有点需要注意的地方。
若是定义了一个变量来保存这个空集合的话,那么没有问题。
在某些情况下,我们经常需要发挥一个空的集合对象,比如说在数据查询时,并不需要发挥一个NULL或是异常,那么就可以返回一个空的集合对象。
JDK提供了两个方式来返回集合对象,那么两者有何区别呢?那就看代码吧!
2.源码解析
[Java] 纯文本查看 复制代码
1
2
3
4
5
6
7
//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()的使用有点需要注意的地方。
若是定义了一个变量来保存这个空集合的话,那么没有问题。
[Java] 纯文本查看 复制代码
1
List<Person> emptyPersonList = Collections.emptyList();
//编译器会自动转化。
若是在某个场景下需要将空对象进行赋值那么就需要如下写法
organization.setPersonList(Collections.<Person> emptyList());
4.BTW
虽然在源码中存在
虽然在源码中存在
[Java] 纯文本查看 复制代码
1
2
3
4
5
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的实现原理还需要考究下!
for (int i =0 ; i < ...)还是 for (Person p : personList)都不会调用到get(int index)这个方法,可以放心使用!前一种方式我们可以很好理解,因为首先是调用了size().后者foreach的实现原理还需要考究下!
5.Note
EmptyList是空的集合,不能进行add等操作。
1 0
- Collections.EMPTY_LIST和Collections.emptyList()简单使用心得
- Collections.EMPTY_LIST和Collections.emptyList()使用
- Collections.emptyList() 和 Collections.EMPTY_LIST的区别
- Java Collections.EMPTY_LIST 和 Collections.emptyList()的区别
- Java Collections.EMPTY_LIST 和 Collections.emptyList()的区别
- Collections的emptyList() emptyMap() emptySet()
- Collections的emptyList() emptyMap() emptySet()
- Collections.emptyList()引发的java.lang.UnsupportedOperationException
- Google Collections 、guava 简单使用
- Collection和Collections的使用
- Collections
- Collections
- Collections
- collections
- Collections
- COLLECTIONS
- Collections
- Collections
- linux内核学习笔记------ARP:地址解析协议
- levelDB实现原理
- LeetCode Simplify Path
- EffectiveJava Item3:使用私有constructor 或者enum实现单例
- 1.7号 java.lang.ClassNotFoundException: Didn't find class "tv.pptv.MainActivity
- Collections.EMPTY_LIST和Collections.emptyList()简单使用心得
- 项目视频讲解_java邮件开发视频教程
- [推荐] VC与我的这四年[奇迹冬瓜] [问题点数:100分,结帖人runner2012] ——有感
- js:prototype
- 用OpenInventor实现的NeHe OpenGL教程-第六课
- 通过指定关键字在手册页中搜索信息
- 【Git笔记】运行man git时报错"No manual entry for git"的解决方法
- 数据结构④-链表
- 服务提供者框架(Service Provider Framework)