例子

  1. public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
  2. "red",
  3. "orange",
  4. "yellow",
  5. "green",
  6. "blue",
  7. "purple");
  8. class Foo {
  9. Set<Bar> bars;
  10. Foo(Set<Bar> bars) {
  11. this.bars = ImmutableSet.copyOf(bars); // defensive copy!
  12. }
  13. }

为啥? 
不可变对象拥有众多好处:

  • Safe for use by untrusted libraries.
  • Thread-safe: can be used by many threads with no risk of race conditions.
  • Doesn't need to support mutation, and can make time and space savings with that assumption. All immutable collection implementations are more memory-efficient than their mutable siblings (analysis)
  • Can be used as a constant, with the expectation that it will remain fixed

防止可变对象拷贝是一个良好的编程习惯,请看这儿:http://www.javapractices.com/topic/TopicAction.do?Id=15 

Making immutable copies of objects is a good defensive programming technique. Guava provides simple, easy-to-use immutable versions of each standard Collection type, including Guava's own Collection variations. 
接下来,Guava说居然JDK的Colletions提供了一套Collections.unmodifiableXXX方法,但不太好用,因此Guava不是在重复造轮子。又强调说,如果你不希望对一个集合进行update,那么最好采用防御性拷贝方式,将它们拷贝到一个不可变的集合中。Guava的集合实现都不支持null的元素(Guva通过研究,发现95%的情况不需要使用null的集合元素),所以如果需要null集合元素,就不能用Guava了。 
咋整? 
可使用如下方法创建不可变集合:

  • using the copyOf method, for example, ImmutableSet.copyOf(set)
  • using the of method, for example, ImmutableSet.of("a", "b", "c") or ImmutableMap.of("a", 1, "b", 2)
  • using a Builder, 看示例:
  1. public static final ImmutableSet<Color> GOOGLE_COLORS =
  2. ImmutableSet.<Color>builder()
  3. .addAll(WEBSAFE_COLORS)
  4. .add(new Color(0, 191, 255))
  5. .build();

使用copeOf(0

  1. ImmutableSet<String> foobar = ImmutableSet.of("foo", "bar", "baz");
  2. thingamajig(foobar);
  3. void thingamajig(Collection<String> collection) {
  4. ImmutableList<String> defensiveCopy = ImmutableList.copyOf(collection);
  5. ...
  6. }

asList 
All immutable collections provide an ImmutableList view via asList(), so -- for example -- even if you have data stored as an ImmutableSortedSet, you can get the kth smallest element with sortedSet.asList().get(k). 

通过asList构造的List通常比直接new ArrayList要快,毕竟它是指定大小的。 

在哪?

Interface JDK or Guava? Immutable Version
Collection JDK ImmutableCollection
List JDK ImmutableList
Set JDK ImmutableSet
SortedSet/NavigableSet JDK ImmutableSortedSet
Map JDK ImmutableMap
SortedMap JDK ImmutableSortedMap
Multiset Guava ImmutableMultiset
SortedMultiset Guava ImmutableSortedMultiset
Multimap Guava ImmutableMultimap
ListMultimap Guava ImmutableListMultimap
SetMultimap Guava ImmutableSetMultimap
BiMap Guava ImmutableBiMap
ClassToInstanceMap Guava ImmutableClassToInstanceMap
Table Guava ImmutableTable

创建集合 
简化集合创建 
原来多麻烦:

  1. Map<String, Integer> counts = new HashMap<String, Integer>();
  2. for (String word : words) {
  3. Integer count = counts.get(word);
  4. if (count == null) {
  5. counts.put(word, 1);
  6. } else {
  7. counts.put(word, count + 1);
  8. }
  9. }

现在:

  1. Multiset<String> wordsMultiset = HashMultiset.create();
  2. wordsMultiset.addAll(words);

Table 
Java代码  

  1. Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
  2. weightedGraph.put(v1, v2, 4);
  3. weightedGraph.put(v1, v3, 20);
  4. weightedGraph.put(v2, v3, 5);
  5. weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20
  6. weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5

工具类

Interface JDK or Guava? Corresponding Guava utility class
Collection JDK Collections2 (avoiding conflict with java.util.Collections)
List JDK Lists
Set JDK Sets
SortedSet JDK Sets
Map JDK Maps
SortedMap JDK Maps
Queue JDK Queues
Multiset Guava Multisets
Multimap Guava Multimaps
BiMap Guava Maps
Table Guava Tables

JDK 7.0之前:

  1. List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<TypeThatsTooLongForItsOwnGood>();

Guava提供如下方式:

  1. List<TypeThatsTooLongForItsOwnGood> list = Lists.newArrayList();
  2. Map<KeyType, LongishValueType> map = Maps.newLinkedHashMap();

JDK 7.0才支持:

  1. List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<>();

Guava提供更多:

  1. Set<Type> copySet = Sets.newHashSet(elements);
  2. List<String> theseElements = Lists.newArrayList("alpha", "beta", "gamma");

指定大小:

  1. List<Type> exactly100 = Lists.newArrayListWithCapacity(100);
  2. List<Type> approx100 = Lists.newArrayListWithExpectedSize(100);
  3. Set<Type> approx100Set = Sets.newHashSetWithExpectedSize(100);  
    类似的:
  1. Multiset<String> multiset = HashMultiset.create();

对象工具类提供的方法,如:

  1. List<Integer> countUp = Ints.asList(1, 2, 3, 4, 5);
  2. List<Integer> countDown = Lists.reverse(theList); // {5, 4, 3, 2, 1}
  3. List<List<Integer>> parts = Lists.partition(countUp, 2); // {{1, 2}, {3, 4}, {5}}

不可变工具类提供的方法,如:

    1. Set<String> wordsWithPrimeLength = ImmutableSet.of("one", "two", "three", "six", "seven", "eight");
    2. Set<String> primes = ImmutableSet.of("two", "three", "five", "seven");
    3. SetView<String> intersection = Sets.intersection(primes, wordsWithPrimeLength); // contains "two", "three", "seven"
    4. // I can use intersection as a Set directly, but copying it can be more efficient if I use it a lot.
    5. return intersection.immutableCopy();

不可变集合 Immutable Collections的更多相关文章

  1. [Guava官方文档翻译] 7. Guava的Immutable Collection(不可变集合)工具 (Immutable Collections Explained)

    我的技术博客经常被流氓网站恶意爬取转载.请移步原文:http://www.cnblogs.com/hamhog/p/3538666.html ,享受整齐的排版.有效的链接.正确的代码缩进.更好的阅读体 ...

  2. Guava学习笔记:Immutable(不可变)集合

    不可变集合,顾名思义就是说集合是不可被修改的.集合的数据项是在创建的时候提供,并且在整个生命周期中都不可改变. 为什么要用immutable对象?immutable对象有以下的优点: 1.对不可靠的客 ...

  3. Immutable(不可变)集合

    Immutable(不可变)集合 不可变集合,顾名思义就是说集合是不可被修改的.集合的数据项是在创建的时候提供,并且在整个生命周期中都不可改变. 为什么要用immutable对象?immutable对 ...

  4. java代码之美(4)---guava之Immutable(不可变)集合

    Immutable(不可变)集合 一.概述 guava是google的一个库,弥补了java语言的很多方面的不足,很多在java8中已有实现,暂时不展开.Collections是jdk提供的一个工具类 ...

  5. java代码(4)---guava之Immutable(不可变)集合

    Immutable(不可变)集合   一,概述 guava是google的一个库,弥补了java语音的很多方面的不足,很多在java8中已有实现,暂时不展开,Collections是jdk提供的一个工 ...

  6. Guava集合--Immutable(不可变)集合

    所谓不可变集合,顾名思义就是定义了之后不可修改的集合. 一.为什么要使用不可变集合 不可变对象有很多优点,包括: 当对象被不可信的库调用时,不可变形式是安全的: 不可变对象被多个线程调用时,不存在竞态 ...

  7. Guava Immutable 不可变集合

    Immutable是为了创建不可变集合使用,不可变集合在很多情况下能提高系统性能.一般使用 .of()或者.builder()<>().put().build()初始化创建不可变集合

  8. 20_集合_第20天(Map、可变参数、Collections)_讲义

    今日内容介绍 1.Map接口 2.模拟斗地主洗牌发牌 01Map集合概述 A:Map集合概述: 我们通过查看Map接口描述,发现Map接口下的集合与Collection接口下的集合,它们存储数据的形式 ...

  9. java 集合Collections 工具类:排序,查找替换。Set、List、Map 的of方法创建不可变集合

    Collections 工具类 Java 提供1个操作 Set List Map 等集合的工具类 Collections ,该工具类里提供了大量方法对集合元素进行排序.查询和修改等操作,还提供了将集合 ...

随机推荐

  1. 使用swiper和吸顶效果代码

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  2. C#中的预处理指令

    C#中的预处理指令 作为预处理中的一对:#region name ,#endregion可能是大家使用得最多的,我也常用它来进行代码分块,在一个比较长的cs文件中,这么做确实是一件可以让你使代码更清晰 ...

  3. 在svg里面画虚线

    使用stroke-dasharray="3 2"  属性,其中3和2分别表示画的长度和间隙的长度 比如 <line x1="0" y1="5&q ...

  4. 题目1049:字符串去特定字符——九度OJ

    题目1049:字符串去特定字符 http://ac.jobdu.com/problem.php?pid=1049 时间限制:1 秒 内存限制:32 兆 题目描述: 输入字符串s和字符c,要求去掉s中所 ...

  5. sublime个人快捷键

    ctrl+alt+f  =  代码格式化(html,js) ctrl+d  =  选中相同内容 alt+shift+w  =  为内容添加新标签 ctrl+shift+a = 选择标签内的内容(再按一 ...

  6. apache使用ssl数字证书

    apache配置: <VirtualHost *:443> ServerName web.p2 .com ProxyPreserveHost On ProxyRequests Off SS ...

  7. mysql四种事务隔离级的说明

    ·未提交读(Read Uncommitted):允许脏读,也就是可能读取到其他会话中未提交事务修改的数据 ·提交读(Read Committed):只能读取到已经提交的数据.Oracle等多数数据库默 ...

  8. Maven 依赖管理

    1  概念介绍 之前我们说过,maven 坐标能够确定一个项目.换句话说,我们可以用它来解决依赖关系.在 POM 中,依赖关系是在 dependencies部分中定义的.在上面的 POM 例子中,我们 ...

  9. IntelliJ IDEA以不同格式导出数据库的数据

    在数据表内容上点击右键,弹出窗口中先选择Data Extractor SQL Inserts,二级菜单会列出导出数据的类型,这里选择SQL Inserts 然后选择Dump Data菜单中的To Fi ...

  10. 预定义宏__GNUC__和_MSC_VER

    一.预定义__GNUC__宏 1 __GNUC__ 是gcc编译器编译代码时预定义的一个宏.需要针对gcc编写代码时, 可以使用该宏进行条件编译. 2 __GNUC__ 的值表示gcc的版本.需要针对 ...