62,615
社区成员
发帖
与我相关
我的任务
分享
public static final Map<String,String> MAP;
static{
Map<String,String> m = new HashMap<String,String>()
m.put("1", "1");
MAP = Collections.unmodifiableMap(m);
}
public static Map<String,String> map = new HashMap<String,String>();
static{
map.put("1", "1");
map = Collections.unmodifiableMap(map);
}
像这样,如果在其他地方调用map.put就会抛出ava.lang.UnsupportedOperationException异常
public static final Map<String,String> map = new HashMap<String,String>(){
{
put("a","1");
put("b","2");
}
};
网上看到的.
设置不可变集合:不可变集合对象只能访问不能修改
Collections有三类方法可返回一个不可变集合:
1、emptyXxx():返回一个空的不可变的集合对象
2、singletonXxx():返回一个只包含指定对象的,不可变的集合对象。
3、unmodifiableXxx():返回指定集合对象的不可变视图
public static void main(String[] args) {
//创建一个空的,不可变的List对象
List unmodList =Collections.emptyList();
//创建一个只有一个元素且不可变的set对象
Set unmodSet =Collections.singleton("唯一的");
Map a=new HashMap();
a.put("语文", 80);
a.put("java", 90);
//返回map对象对应的不可变版本
Map unmodMap =Collections.unmodifiableMap(a);
//以下代码都将引发UnsupportedOperationException异常
unmodList.add("hello");
unmodSet.add("kitty");
unmodMap.put("语文", 70)
}
另外,你需要注意:假如Map里面放的是引用类型数据[比如对象],不可变性可能会发生改变.
public static final Map<String,String> map=new HashMap<String, String>();
static{
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
}
public static void main(String[] args) {
System.out.println(map);
}