码迷,mamicode.com
首页 > 其他好文 > 详细

Google Guava 学习记录《4》Immutable Set

时间:2015-09-14 11:52:42      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

Immutable objects have many advantages, including:

  • 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

 

Example

public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
  "red",
  "orange",
  "yellow",
  "green",
  "blue",
  "purple");

class Foo {
  final ImmutableSet<Bar> bars;
  Foo(Set<Bar> bars) {
    this.bars = ImmutableSet.copyOf(bars); // defensive copy!
  }
}

不可变的集合,其实是保证了最重要的安全性,还有性能上的提升。

也可以对这种集合做排序,比如调用ImmutableSortedSet  这个排序是在构造函数阶段排序的。

 

Google Guava 学习记录《4》Immutable Set

标签:

原文地址:http://www.cnblogs.com/-Doraemon/p/4806701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!