final只能保证不能被再次初始化,其中的值是可以变化的。
现在是需要一个集合中的值不能被修改。整理了以下几种方法:
可以用Collections和Guava
Map----------------------------------->
Collections.unmodifiableMap(map);
或者:
private final static ImmutableMap<Integer, Integer> map2 = ImmutableMap<Integer,Integer>builder().put(1,2).put(3,4).put(5,6).build();
List/Set------------------------------->
private final static ImmutableList list = ImmutableList.of(1, 2, 3); // 这样被初始化之后 list是不能被改变
private final static ImmutableSet set = ImmutableSet.copyOf(list); // 这样被初始化之后set是不能被改变的