Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Collections.unmodifiableMap performance critical?

I have a hashmap<String, String> which contains around one thousand entries. Now I have to expose it in such way that it cannot be modified outside class. So I wrote like

public static Map<String, String> getResponseCodeSource()
{
    return Collections.unmodifiableMap(codeMsgMap); 
}

This method is called very frequently. My questions are
1. Will this cause performance issue?
2.Is method (unmodifiableMap) iterating over Map or this will perform its activity in O(constant) complexity ?

like image 764
user811602 Avatar asked Mar 20 '15 08:03

user811602


People also ask

What is unmodifiableMap in Java?

The unmodifiableMap() method of java. util. Collections class is used to return an unmodifiable view of the specified map.


2 Answers

It's a very thin implementation:

public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
    return new UnmodifiableMap<>(m);
}

and constructor code:

UnmodifiableMap(Map<? extends K, ? extends V> m) {
    if (m==null)
        throw new NullPointerException();
    this.m = m;
}

So as you see complexity is O(1).

like image 195
Sergey Pauk Avatar answered Nov 15 '22 04:11

Sergey Pauk


The Map returned from Collections.unmodifiableMap(Map) will be a thin proxy to the real underlying map with some methods disabled (put etc.). There is no reason to expect it to take a copy of the underlying map.

Returns: an unmodifiable view of the specified map.

Remember however that the unmodifiable map is only a view of the underlying map so changes in the underlying map will be reflected in the unmodifiable one. It would therefore be safe to do:

static final Map<String,String> codeMsgMap = new HashMap<>();
// Changes in the above map will be reflected here.
static final Map<String,String> unmodifiableCodeMsgMap = Collections.unmodifiableMap(codeMsgMap);

public static Map<String, String> getResponseCodeSource() {
    return unmodifiableCodeMsgMap;
}

On the complexity question Sergey Pauk covers that nicely.

like image 44
OldCurmudgeon Avatar answered Nov 15 '22 05:11

OldCurmudgeon