Returning an unmodifiable map

空扰寡人 提交于 2019-12-01 02:25:52

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.

I created a small test program and my program threw an 'UnsupportedOperationException' when I tried to put data in.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!