Guava - Collections - Immutable collections
通篇看下来,主要讲Immutable Collections在防御性编程上的应用
首先要先了解下 defensive copy
http://blog.csdn.net/tounaobun/article/details/8607174
官方wiki的介绍也基本是讲 Immutable Collections主要用在防御性编程上会使程序更安全,并且对比了jdk的Collections.unmodifiableXXX methods
优势:
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
对比JDK的
The JDK provides Collections.unmodifiableXXX methods, but in our opinion, these can be
- unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies
- unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection
- inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.
然后介绍了几种创建Immutable Collection 的方法(详情可参见官网)
总结,可能更适合“高级程序员”吧,目前就当看看,储备知识,而且很多时候复制后就是希望修改的(并不是设计为防御性的)
实用性:中