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();