不可变集合 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
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();
扩展工具类
略了,看:
http://code.google.com/p/guava-libraries/wiki/CollectionHelpersExplained
分享到:
相关推荐
包含翻译后的API文档:guava-11.0.2-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.google.guava:guava:11.0.2; 标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开...
包含翻译后的API文档:guava-23.0-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.google.guava:guava:23.0; 标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开...
包含翻译后的API文档:guava-20.0-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.google.guava:guava:20.0; 标签:google、guava、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开...
包含翻译后的API文档:guava-17.0-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.google.guava:guava:17.0; 标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开...
包含翻译后的API文档:guava-18.0-javadoc-API文档-中文(简体)版.zip 对应Maven信息:groupId:com.google.guava,artifactId:guava,version:18.0 使用方法:解压翻译后的API文档,用浏览器打开“index.html”...
包含翻译后的API文档:guava-20.0-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:com.google.guava:guava:20.0; 标签:google、guava、jar包、java、中英对照文档; 使用方法:解压翻译后的API文档,用...
包含翻译后的API文档:guava-19.0-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:com.google.guava:guava:19.0; 标签:google、guava、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用...
赠送原API文档:guava-18.0-javadoc.jar 赠送源代码:guava-18.0-sources.jar 包含翻译后的API文档:guava-18.0-javadoc-API文档-中文(简体)-英语-对照版.zip 对应Maven信息:groupId:com.google.guava,...
Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, 等等. 这些高质量的 API 可以使你...
包含翻译后的API文档:guava-16.0.1-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.google.guava:guava:16.0.1; 标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开...
包含翻译后的API文档:guava-19.0-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.google.guava:guava:19.0; 标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开...
Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, 等等. 这些高质量的 API 可以使你...
包含翻译后的API文档:guava-12.0.1-javadoc-API文档-中文(简体)-英语-对照版.zip 对应Maven信息:groupId:com.google.guava,artifactId:guava,version:12.0.1 使用方法:解压翻译后的API文档,用浏览器打开...
包含翻译后的API文档:guava-22.0-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.google.guava:guava:22.0; 标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开...
标签:google、guava、jar包、java、API文档、中文版; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心...
包含翻译后的API文档:guava-28.0-android-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.google.guava:guava:28.0-android; 标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,...
guava-API文档
包含翻译后的API文档:guava-17.0-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:com.google.guava:guava:17.0; 标签:google、guava、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用...
Guava是Google开发的一个Java库,它包含许多Google的核心库,如集合、缓存、并发库、原生类型支持、字符串处理、I/O等。这个库极大地丰富了Java的生态系统,提高了开发效率。本文将详细讲解Guava的一些常用API及其在...
包含翻译后的API文档:guava-24.1-jre-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:com.google.guava:guava:24.1-jre; 标签:google、guava、中英对照文档、jar包、java; 使用方法:解压翻译后的API...