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 ?
The unmodifiableMap() method of java. util. Collections class is used to return an unmodifiable view of the specified map.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With