不可变集合 Immutable Collections
例子
- public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
- "red",
- "orange",
- "yellow",
- "green",
- "blue",
- "purple");
- class Foo {
- Set<Bar> bars;
- Foo(Set<Bar> bars) {
- this.bars = ImmutableSet.copyOf(bars); // defensive copy!
- }
- }
为啥?
不可变对象拥有众多好处:
- 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, 看示例:
- public static final ImmutableSet<Color> GOOGLE_COLORS =
- ImmutableSet.<Color>builder()
- .addAll(WEBSAFE_COLORS)
- .add(new Color(0, 191, 255))
- .build();
使用copeOf(0
- ImmutableSet<String> foobar = ImmutableSet.of("foo", "bar", "baz");
- thingamajig(foobar);
- void thingamajig(Collection<String> collection) {
- ImmutableList<String> defensiveCopy = ImmutableList.copyOf(collection);
- ...
- }
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 |
创建集合
简化集合创建
原来多麻烦:
- Map<String, Integer> counts = new HashMap<String, Integer>();
- for (String word : words) {
- Integer count = counts.get(word);
- if (count == null) {
- counts.put(word, 1);
- } else {
- counts.put(word, count + 1);
- }
- }
现在:
- Multiset<String> wordsMultiset = HashMultiset.create();
- wordsMultiset.addAll(words);
Table
Java代码 ![]()
- Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
- weightedGraph.put(v1, v2, 4);
- weightedGraph.put(v1, v3, 20);
- weightedGraph.put(v2, v3, 5);
- weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20
- 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之前:
- List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<TypeThatsTooLongForItsOwnGood>();
Guava提供如下方式:
- List<TypeThatsTooLongForItsOwnGood> list = Lists.newArrayList();
- Map<KeyType, LongishValueType> map = Maps.newLinkedHashMap();
JDK 7.0才支持:
- List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<>();
Guava提供更多:
- Set<Type> copySet = Sets.newHashSet(elements);
- List<String> theseElements = Lists.newArrayList("alpha", "beta", "gamma");
指定大小:
- List<Type> exactly100 = Lists.newArrayListWithCapacity(100);
- List<Type> approx100 = Lists.newArrayListWithExpectedSize(100);
- Set<Type> approx100Set = Sets.newHashSetWithExpectedSize(100);
类似的:
- Multiset<String> multiset = HashMultiset.create();
对象工具类提供的方法,如:
- List<Integer> countUp = Ints.asList(1, 2, 3, 4, 5);
- List<Integer> countDown = Lists.reverse(theList); // {5, 4, 3, 2, 1}
- List<List<Integer>> parts = Lists.partition(countUp, 2); // {{1, 2}, {3, 4}, {5}}
不可变工具类提供的方法,如:
- Set<String> wordsWithPrimeLength = ImmutableSet.of("one", "two", "three", "six", "seven", "eight");
- Set<String> primes = ImmutableSet.of("two", "three", "five", "seven");
- SetView<String> intersection = Sets.intersection(primes, wordsWithPrimeLength); // contains "two", "three", "seven"
- // I can use intersection as a Set directly, but copying it can be more efficient if I use it a lot.
- return intersection.immutableCopy();
不可变集合 Immutable Collections的更多相关文章
- [Guava官方文档翻译] 7. Guava的Immutable Collection(不可变集合)工具 (Immutable Collections Explained)
我的技术博客经常被流氓网站恶意爬取转载.请移步原文:http://www.cnblogs.com/hamhog/p/3538666.html ,享受整齐的排版.有效的链接.正确的代码缩进.更好的阅读体 ...
- Guava学习笔记:Immutable(不可变)集合
不可变集合,顾名思义就是说集合是不可被修改的.集合的数据项是在创建的时候提供,并且在整个生命周期中都不可改变. 为什么要用immutable对象?immutable对象有以下的优点: 1.对不可靠的客 ...
- Immutable(不可变)集合
Immutable(不可变)集合 不可变集合,顾名思义就是说集合是不可被修改的.集合的数据项是在创建的时候提供,并且在整个生命周期中都不可改变. 为什么要用immutable对象?immutable对 ...
- java代码之美(4)---guava之Immutable(不可变)集合
Immutable(不可变)集合 一.概述 guava是google的一个库,弥补了java语言的很多方面的不足,很多在java8中已有实现,暂时不展开.Collections是jdk提供的一个工具类 ...
- java代码(4)---guava之Immutable(不可变)集合
Immutable(不可变)集合 一,概述 guava是google的一个库,弥补了java语音的很多方面的不足,很多在java8中已有实现,暂时不展开,Collections是jdk提供的一个工 ...
- Guava集合--Immutable(不可变)集合
所谓不可变集合,顾名思义就是定义了之后不可修改的集合. 一.为什么要使用不可变集合 不可变对象有很多优点,包括: 当对象被不可信的库调用时,不可变形式是安全的: 不可变对象被多个线程调用时,不存在竞态 ...
- Guava Immutable 不可变集合
Immutable是为了创建不可变集合使用,不可变集合在很多情况下能提高系统性能.一般使用 .of()或者.builder()<>().put().build()初始化创建不可变集合
- 20_集合_第20天(Map、可变参数、Collections)_讲义
今日内容介绍 1.Map接口 2.模拟斗地主洗牌发牌 01Map集合概述 A:Map集合概述: 我们通过查看Map接口描述,发现Map接口下的集合与Collection接口下的集合,它们存储数据的形式 ...
- java 集合Collections 工具类:排序,查找替换。Set、List、Map 的of方法创建不可变集合
Collections 工具类 Java 提供1个操作 Set List Map 等集合的工具类 Collections ,该工具类里提供了大量方法对集合元素进行排序.查询和修改等操作,还提供了将集合 ...
随机推荐
- 理解MySQL——复制(Replication)
1.复制概述 1.1.复制解决的问题数据复制技术有以下一些特点:(1) 数据分布(2) 负载平衡(load balancing)(3) 备份(4) 高可用性(high avai ...
- 021. asp.net两个DataSet数据集的合并
protected void Page_Load(object sender, EventArgs e) { DataSet dsSource = new DataSet(); //创建源数据集 Da ...
- Windows Azure 生成证书
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64>makecert -sky exchange -r -n &qu ...
- android 如何让文本中某个关键字高亮显示?
TextView tv = (TextView) findViewById(R.id.hello);SpannableString s = new SpannableString(getResourc ...
- IOS:被误解的MVC和被神化的MVVM
MVC的历史 MVC,全称是 Model View Controller,是模型 (model)-视图 (view)-控制器 (controller) 的缩写.它表示的是一种常见的客户端软件开发框架. ...
- Zabbix 教程
Zabbix 教程http://blog.csdn.net/linuxlsq/article/details/52606086 MySQL在以下几种情况会创建临时表:1.UNION查询:2.用到TEM ...
- eclipse打包jar文件(含外部jar包)的方法
在项目发布前,使用eclipse导出普通的jar包时,如果配置不好,在运行命令Java -jar /test.jar 时可能会出现如下三类错误信息: 1.no main manifest attrib ...
- 封装类的方式访问数据库(封装字符串、json)
<?php class DBDA { public $host="localhost";//服务器地址 public $uid="root";//用户名 ...
- 【linux】wc命令
Linux系统中的wc(Word Count)命令的功能为统计指定文件中的字节数.字数.行数,并将统计结果显示输出. 1.命令格式: wc [选项][文件] 2.命令参数: -c char统计字节数. ...
- 剑指offer系列30-----删除链表中重复的节点
[题目]在一个排序的链表中,存在重复的结点, * 请删除该链表中重复的结点,重复的结点不保留,返回链表头指针. * 例如,链表1->2->3->3->4->4->5 ...