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

0 0
原创粉丝点击