1
package googleCollections;
2
3
import java.util.ArrayList;
4
import java.util.Arrays;
5
import java.util.Collections;
6
import java.util.List;
7
import java.util.Map.Entry;
8
9
import com.google.common.collect.ImmutableList;
10
import com.google.common.collect.ImmutableMap;
11
import com.google.common.collect.ImmutableSet;
12
13
/**
14
* Copyright (C): 2009
15
* @author 陳新漢
16
* @version 創建時間:Jan 12, 2010 11:10:05 PM
17
*/
18
19
/**
20
* 不可變集合類
21
* 適合作為內容數據不可變的容器類
22
* 例如:常量數組、常量Map等等。
23
*
24
* 注意:為了實現不可變集合,JDK 5.0里面是通過Collections.unmodifiableList(list)實現的!
25
*/
26
public class ImmutableListTest {
27
28
public static final List<String> imlist; //以前實現(方式一)
29
public static final List<String> imlist2; //以前實現(方式二)
30
31
static{
32
List<String> list=new ArrayList<String>();
33
list.add("a");
34
list.add("b");
35
list.add("c");
36
imlist=Collections.unmodifiableList(list); //通過這種方式實現不可變的集合,以前實現(方式一)
37
imlist2=Collections.unmodifiableList(Arrays.asList("a","b","c")); //或者,通過這種方式實現不可變的集合,以前實現(方式二)
38
}
39
40
/**
41
* @param args
42
*/
43
public static void main(String[] args)
44
{
45
//常量列表
46
ImmutableList<String> imlist=ImmutableList.of("a", "b", "c");
47
//imlist.add("d"); //注意,編譯會報異常
48
for(String s:imlist){
49
System.out.println(s);
50
}
51
52
//常量Map
53
ImmutableMap<String,String> immap=new ImmutableMap.Builder<String,String>()
54
.put("a","1")
55
.put("b","2")
56
.put("c", "3")
57
.build();
58
for(Entry<String,String> e:immap.entrySet()){
59
System.out.println(e.getKey()+"="+e.getValue());
60
}
61
62
//常量Set
63
ImmutableSet<String> imset=ImmutableSet.of("a","b","c");
64
for(String s:imset){
65
System.out.println(s);
66
}
67
}
68
69
}
70

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

(友情提示:本博文章歡迎轉載,但請注明出處:hankchen,http://www.tkk7.com/hankchen)