首页 > 其他 > 详细

Google Guava 学习记录《4》Immutable Set

时间:2015-09-14 11:52:11      阅读:219      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!