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 这个排序是在构造函数阶段排序的。