private final int a = 123;
private static final Map<Integer, String> map = Maps.newHashMap();
static {
map.put(1, "one");
map.put(2, "two");
}
public static void main(String[] args) {
map.put(1,"three");
log.info("{}", map.get(1));
}
static {
map.put(1, "one");
map.put(2, "two");
map = Collections.unmodifiableMap(map);
}
public static void main(String[] args) {
log.info("{}", map.get(1));
}
static {
map.put(1, "one");
map.put(2, "two");
map = Collections.unmodifiableMap(map);
}
public static void main(String[] args) {
map.put(1, "three");
log.info("{}", map.get(1));
}
Collections.unmodifiableXXX:Collection、List、Set、Map...
Guava:ImmutableXXX:Collection、List、Set、Map...
private final static ImmutableList<Integer> list = ImmutableList.of(1, 2, 3); // 這樣被初始化之後 list是不能被改變
private final static ImmutableSet set = ImmutableSet.copyOf(list); // 這樣被初始化之後set是不能被改變的
public static void main(String[] args) {
list.add(123);
set.add(222);
}
}
上述代碼中的list和set不能再被改變。
注意:guava中的map的寫法有點不一樣如下:
private final static ImmutableMap<Integer, Integer> map = ImmutableMap.of(1,2,3,4,5, 6);
private final static ImmutableMap<Integer, Integer> map2 = ImmutableMap.<Integer, Integer>builder().put(1,2).put(3,4).put(5,6).build();