Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an unmodifiable map

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?

like image 317
mre Avatar asked Aug 15 '11 15:08

mre


2 Answers

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.

like image 142
Jon Skeet Avatar answered Nov 15 '22 15:11

Jon Skeet


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?

like image 37
Hunter McMillen Avatar answered Nov 15 '22 14:11

Hunter McMillen