问题描述
使用,我试图返回一个不可修改的地图视图。假设我有以下方法,
public final Map< Foo,Bar> getMap(){
...
return Collections.unmodifiableMap(map);
}
为什么在别的地方执行以下操作,
Map< Foo,Bar> map = getMap();
map.put(...);
这不会抛出一个。有人可以解释一下,还是建议如何成功地返回真正不可修改的地图?
你确定你不是掩饰你的例外吗?这样做很好,因为它会引发 UnsupportedOperationException
:
import java .util *。
public class Test {
public static void main(String [] args){
Map< String,String> map = getMap();
map.put(a,b);
}
public static final Map< String,String> getMap(){
Map< String,String> map = new HashMap< String,String>();
map.put(x,y);
return Collections.unmodifiableMap(map);
}
}
我建议您打印出 map.getClass()
对方法的返回值 - 我会期望它是一个 UnmodifiableMap
。 / p>
Using Collections.unmodifiableMap(...)
, I'm trying to return an unmodifiable view of a map. Let's say I have the following method,
public final Map<Foo, Bar> getMap(){
...
return Collections.unmodifiableMap(map);
}
Why is it legal elsewhere to do the following,
Map<Foo, Bar> map = getMap();
map.put(...);
This doesn't throw an UnsupportedOperationException
like I thought it would. Can someone please explain this, or suggest how I can successfully return a truly unmodifiable map?
Are you sure you're not masking your exceptions somehow? This works absolutely fine, in that it throws UnsupportedOperationException
:
import java.util.*;
public class Test {
public static void main(String[] args) {
Map<String, String> map = getMap();
map.put("a", "b");
}
public static final Map<String, String> getMap(){
Map<String, String> map = new HashMap<String, String>();
map.put("x", "y");
return Collections.unmodifiableMap(map);
}
}
I suggest you print out map.getClass()
on the return value of the method - I would expect it to be an UnmodifiableMap
.
这篇关于返回不可修改的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!