一航厚、簡(jiǎn)介
官網(wǎng)對(duì)Immutable Collections
的簡(jiǎn)介如下:
Immutable collections, for defensive programming, constant collections, and improved efficiency.
大致意思就是可以通過(guò)不可變集合應(yīng)用于防御式編程寥掐、常量集合以及提高效率.
二、為什么使用 Immutable Collections?
guava gitlab wiki上給出的解釋是不可變對(duì)象有很多優(yōu)點(diǎn)鳍寂,包括:
1、對(duì)于不受信任的庫(kù)來(lái)說(shuō)是安全的。
2式廷、線程安全:可以由許多線程使用承冰,沒(méi)有競(jìng)爭(zhēng)條件的風(fēng)險(xiǎn)华弓。
3、不需要支持變異困乒,可以節(jié)省時(shí)間和空間的假設(shè)寂屏。所有不可變集合實(shí)現(xiàn)都比它們的可變同類(lèi)型的實(shí)現(xiàn)更節(jié)省內(nèi)存。(分析)
3、可以用作常數(shù)迁霎,期望它保持不變吱抚。
4、創(chuàng)建對(duì)象的不可變副本是一種很好的防御性編程技術(shù)考廉。Guava提供每個(gè)標(biāo)準(zhǔn)集合類(lèi)型的簡(jiǎn)單秘豹、易于使用的不可變版本,包括Guava自己的集合變體昌粤。
當(dāng)我們不期望修改一個(gè)集合既绕,或者期望一個(gè)集合保持不變時(shí),將它復(fù)制到一個(gè)不可變的集合是一個(gè)很好的辦法涮坐。
重要提示:每個(gè)Guava不可變集合實(shí)現(xiàn)都拒絕null值的凄贩。谷歌的內(nèi)部代碼庫(kù)進(jìn)行了詳盡的研究,結(jié)果表明袱讹,在大約5%的情況下疲扎,集合中允許使用null元素,而在95%的情況下捷雕,在null上快速失敗是最好的方法椒丧。如果需要使用null值,可以考慮使用集合救巷。
三壶熏、如何使用 Immutable Collections?
Immutable Collections
支持多種創(chuàng)建方式
1、通過(guò)of()
方法創(chuàng)建
通過(guò)of()
方法創(chuàng)建的不可變集合,除了已排序的集合外征绸,其他的都是按照時(shí)間構(gòu)建來(lái)排序的久橙;
簡(jiǎn)單實(shí)驗(yàn):
ImmutableList<String> createByOf = ImmutableList.of("a", "b");
思考點(diǎn) - 為什么是以這種方式創(chuàng)建?為什么當(dāng)節(jié)點(diǎn)是13個(gè)節(jié)點(diǎn)的時(shí)候使用數(shù)組管怠?
/**
* Returns an immutable list containing a single element. This list behaves
* and performs comparably to {@link Collections#singleton}, but will not
* accept a null element. It is preferable mainly for consistency and
* maintainability of your code.
*
* @throws NullPointerException if {@code element} is null
*/
public static <E> ImmutableList<E> of(E element) {
return new SingletonImmutableList<E>(element);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2) {
return construct(e1, e2);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
@SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) {
Object[] array = new Object[12 + others.length];
array[0] = e1;
array[1] = e2;
array[2] = e3;
array[3] = e4;
array[4] = e5;
array[5] = e6;
array[6] = e7;
array[7] = e8;
array[8] = e9;
array[9] = e10;
array[10] = e11;
array[11] = e12;
System.arraycopy(others, 0, array, 12, others.length);
return construct(array);
}
2淆衷、通過(guò)copyOf()
方法創(chuàng)建
簡(jiǎn)單實(shí)驗(yàn):
ImmutableList<String> createByOf = ImmutableList.of("a", "b");
ImmutableList<String> createByCopyOf = ImmutableList.copyOf(normalList);
3、通過(guò)builder()
方法創(chuàng)建
簡(jiǎn)單實(shí)驗(yàn)
ImmutableList<String> createByBuilder = ImmutableList.<String>builder()
.add("A")
.add("B")
.build();
未完待續(xù)......