views:

65

answers:

2

I have a map of constants, like this:

private static Map<String, Character> _typesMap =
        new HashMap<String, Character>() {
        {
            put ("string", 'S');
            put ("normalizedString", 'N');
            put ("token", 'T');
            // (...)
        }

Do I really need to use Collections.unmodifiableMap() to create this map? What is the advantage of using it? Are there any disadvantages of not using it, besides the obvious fact that they are not really becoming constant?

+9  A: 

Collections.unmodifiableMap guarantees that the map will not be modified. It's mostly useful if you want to return a read-only view of an internal map from a method call, e.g:

class A {
    private Map importantData;

    public Map getImportantData() {
        return Collections.unmodifiableMap(importantData);
    }
}

This gives you a fast method that does not risk the client changing your data. It's much faster and more memory efficient than returning a copy of the map. If the client really does want to modify the returned value then they can copy it themselves, but changes to the copy won't be reflected in A's data.

If you are not returning map references to anyone else then don't bother making it unmodifiable unless you are paranoid about making it immutable. You can probably trust yourself to not change it.

Cameron Skinner
"It's much faster and more memory efficient than returning a copy of the map." -- that's what I wanted to know. :-)
Paulo Guedes
Feel free to mark that as "accepted answer" then :)
Cameron Skinner
A: 

Wrapping the Map is to ensure the caller won't change the collection. While this is useful in testing, you really should find this sort of bug there, it may not be so useful in production. A simple workaround is to have your own wrapper like.

public static <K,V> Map<K,V> unmodifiableMap(Map<K,V> map) {
   assert (map = Collections.unmodifiableMap(map)) != null;
   return map;
}

This only wraps the map when assertions are turned on.

Peter Lawrey
"it may not be so useful in production" -- why? That's my point, is it useful? is it really necessary?
Paulo Guedes
If you test it properly in a test environment, this should not be needed in production because you have checked that the collection is never modified.
Peter Lawrey