Collections.unmodifiableXXX()方法实例

unmodifiableSet() 方法返回指定set的不可修改视图。
声明

以下是java.util.Collections.unmodifiableSet()方法的声明。

public static boolean addAll(Collection<? super T> c, T.. a)

参数

s–这是一个不可修改视图是要返回的集合。

返回值

在方法调用返回指定set的不可修改视图。

例子

下面的例子显示java.util.Collections.unmodifiableSet()方法的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.yiibai;
public class CollectionsDemo {
public static void main(String[] s) {
// create set
Set<String> set = new HashSet<String>();
// populate the set
set.add("Welcome");
set.add("to");
set.add("TP");
System.out.println("Initial set value: "+set);
// create unmodifiable set
Set unmodset = Collections.unmodifiableSet(set);
// try to modify the set
unmodset.add("Hello");
}
}


Collections.unmodifiableXXX() 来做一个不可修改的集合。例如你要构造存储常量的 Set,你可以这样来做 :

1
2
Set<String> set = new HashSet<String>(Arrays.asList(new String[]{"RED", "GREEN"}));
Set<String> unmodifiableSet = Collections.unmodifiableSet(set);

这看上去似乎不错,因为每次调 unmodifiableSet.add() 都会抛出一个 UnsupportedOperationException。感觉安全了?慢!如果有人在原来的 set 上 add 或者 remove 元素会怎么样?结果 unmodifiableSet 也是被 add 或者 remove 元素了。而且构造这样一个简单的 set 写了两句长的代码。下面看看 ImmutableSet 是怎么来做地更安全和简洁 :

immutableSet = ImmutableSet.of("RED", "GREEN");```
1
2
3
4
就这样一句就够了,而且试图调 add 方法的时候,它一样会抛出 UnsupportedOperationException。重要的是代码的可读性增强了不少,非常直观地展现了代码的用意。如果像之前这个代码保护一个 set 怎么做呢?你可以 :
``` ImmutableSet<String> immutableSet = ImmutableSet.copyOf(set);

从构造的方式来说,ImmutableSet 集合还提供了 Builder 模式来构造一个集合 :

builder = ImmutableSet.builder();
1
ImmutableSet<String> immutableSet = builder.add("RED").addAll(set).build();

在这个例子里面 Builder 不但能加入单个元素还能加入既有的集合。
除此之外,Guava Collections 还提供了各种 Immutable 集合的实现:ImmutableList,ImmutableMap,ImmutableSortedSet,ImmutableSortedMap