返回不可修改的地图
使用 Collections.unmodifyingMap( ...)
,我正在尝试返回地图的不可修改视图。假设我有以下方法,
public final Map<Foo, Bar> getMap(){
...
return Collections.unmodifiableMap(map);
}
为什么在其他地方执行以下操作是合法的,
Map<Foo, Bar> map = getMap();
map.put(...);
这不会抛出 UnsupportedOperationException
就像我想象的那样。有人可以解释一下这一点,或者建议我如何成功返回真正不可修改的地图吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你确定你没有以某种方式掩盖你的异常吗?这绝对没问题,因为它会抛出
UnsupportedOperationException
:我建议您在方法的返回值上打印出
map.getClass()
- 我希望 /em> 它是一个UnmodifyingMap
。Are you sure you're not masking your exceptions somehow? This works absolutely fine, in that it throws
UnsupportedOperationException
:I suggest you print out
map.getClass()
on the return value of the method - I would expect it to be anUnmodifiableMap
.我创建了一个小型测试程序,当我尝试将数据放入时,我的程序抛出了“UnsupportedOperationException”。
代码:
你在课堂上还做什么?
I created a small test program and my program threw an 'UnsupportedOperationException' when I tried to put data in.
code:
What else are you doing in your class?
一定还有其他问题。将其包装为不可修改的映射后,您无法在该映射中
放入
某些内容。我还建议返回,
否则在使用 -Xlint:unchecked 编译代码时会收到“未检查”警告。
There must be something else wrong. There's no way you can
put
something in that map after you wrapped it as an unmodifiable map.I would also suggest to return
otherwise you will get "unchecked" warnings when compiling your code with -Xlint:unchecked.