简体   繁体   English

返回不可修改的地图

[英]Returning an unmodifiable map

Using Collections.unmodifiableMap(...) , I'm trying to return an unmodifiable view of a map. 使用Collections.unmodifiableMap(...) ,我试图返回一个不可修改的地图视图。 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. 这不会像我想的那样抛出UnsupportedOperationException 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 : 这非常正常,因为它抛出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 . 我建议你在方法的返回值上打印出map.getClass() - 我希望它是一个UnmodifiableMap

I created a small test program and my program threw an 'UnsupportedOperationException' when I tried to put data in. 我创建了一个小测试程序,当我尝试将数据放入时,我的程序抛出了'UnsupportedOperationException'。

code: 码:

import java.util.*;

public class TestUnmodifiableMap
{
    Map<Integer, String> myMap;

    public TestUnmodifiableMap()
    {
        myMap = new HashMap<Integer, String>();
    }

    public final Map<Integer, String> getMap()
    {
        return Collections.unmodifiableMap(myMap);
    }

    public static void main(String[] args)
    {
        TestUnmodifiableMap t = new TestUnmodifiableMap();
        Map<Integer, String> testMap = t.getMap();

        testMap.put(new Integer("1"), "Hello");
    }
}

What else are you doing in your class? 你在课堂上还做了什么?

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. 在将其包装为不可修改的地图后,您无法在该地图中put某些内容。

I would also suggest to return 我还建议你回来

return Collections.<Foo, Bar>unmodifiableMap(map);

otherwise you will get "unchecked" warnings when compiling your code with -Xlint:unchecked. 否则,在使用-Xlint编译代码时,您将收到“未选中”警告:未选中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM