Collections的emptyList() emptyMap() emptySet()
来源:互联网 发布:php打印前一天时间 编辑:程序博客网 时间:2024/06/08 12:39
Collections的emptyList() emptyMap() emptySet()
在看Collections时看到这三个方法
Collections.emptySet() Collections.emptyList() Collections.emptyMap()
会生成指定类型的空List Set Map,而且是不可变的,如进行add()操作会报java.lang.UnsupportedOperationException,返回这样不可变的空集合有什么作用呢?
方法内部会返回static final成员,创建后相当于常量可重复引用,当需要使用一个空集合时不用new去分配内存,比如一个测试用例API接口就需要一个
Map<String,Object>,
若此时只需要一个空map跑用例,直接用Collections.emptyMap()作为参数即可防止空指针出现,当你的代码需要一个集合而这个集合可能不存在,此时尽量使用空集合而不是null,因为集合一个常用的操作就是遍历,你不知道你返回的结果在后续会不会被遍历。比如一个查询步骤返回一个集合,当返回一个空集合是就可以用这类方法,还可以防止后续对这个空集合再做add操作
参考Effactive JAVA 43条:返回0长度的数组或者集合,而不是null
对于泛型集合无需指定其类型参数,如
Map<Foo, Comparable<? extends Bar>> fooBarMap = new HashMap<Foo, Comparable<? extends Bar>>();
只要Map<Foo, Comparable<? extends Bar>> fooBarMap = Collections.emptyMap();
即可,起到简化代码作用使用集合的一个好习惯就是使用 immutable collection,参考 http://stackoverflow.com/questions/214714/mutable-vs-immutable-objects/214718#214718
@Testpublic void test_emptySet(){ Set<String> s1 = new HashSet<String>(); Set<File> s2 = new LinkedHashSet<File>(); Set<Integer> s3 = new TreeSet<Integer>(); assertTrue(s1.equals(Collections.emptySet())); assertTrue(s2.equals(Collections.emptySet())); assertTrue(s3.equals(Collections.emptySet())); s1.add("abc"); assertFalse(s1.equals(Collections.emptySet())); s1.clear(); assertTrue(s1.equals(Collections.emptySet()));}
参考
http://www.cnblogs.com/booth-sun/p/5625764.html
https://coderanch.com/t/536728/java/java/Collections-emptySet-Collections-emptyList-Collections
http://stackoverflow.com/questions/14846920/collections-emptymap-vs-new-hashmap
- Collections的emptyList() emptyMap() emptySet()
- Collections的emptyList() emptyMap() emptySet()
- Java之Collections.emptyList()、emptySet()、emptyMap()的作用和好处以及要注意的地方。
- Collection工具类中的 emptyMap() 、emptySet() 、emptySet()
- Collections.emptyList() 和 Collections.EMPTY_LIST的区别
- Collections.emptyList()引发的java.lang.UnsupportedOperationException
- Java Collections.EMPTY_LIST 和 Collections.emptyList()的区别
- Java Collections.EMPTY_LIST 和 Collections.emptyList()的区别
- Collections.EMPTY_LIST和Collections.emptyList()使用
- Collections.EMPTY_LIST和Collections.emptyList()简单使用心得
- java 异常java.lang.UnsupportedOperationException ---EmptyList此集合竟然没有相应的add,remove等方法
- Collections Collections.synchronizedCollection 集合的同步控制
- 对Collections的理解
- hibernate的collections介绍
- collections的学习知识
- collections的学习知识
- Collections的实用方法
- 对Collections的总结
- linux随笔
- 五音不全中,五音是指什么
- 要么读书,要么健身,要么恋爱(六)白夜行
- Live Archive 5659 The Last Puzzle
- CentOS 6.3下Samba服务器的安装与配置
- Collections的emptyList() emptyMap() emptySet()
- 实践反馈-hierarchyviewer
- 常用查看Linux系统信息命令
- js模版引擎handlebars.js
- 2016校招真题汇总2:简单错误记录
- 微软面试100题---寻找和为定值的多个数
- 2016年最值得学习的五大开源项目
- Reverse Words in a String
- 函数式编程