use*_*602 5 java collections hashmap
我有一个hashmap<String, String>包含大约一千个条目.现在我必须以不能在课外修改的方式公开它.所以我写得像
public static Map<String, String> getResponseCodeSource()
{
return Collections.unmodifiableMap(codeMsgMap);
}
Run Code Online (Sandbox Code Playgroud)
非常频繁地调用此方法.我的问题是
1.这是否会导致性能问题?
2.迭代Map的方法(unmodifiableMap)是否会以O(常量)复杂度执行其活动?
这是一个非常薄的实现:
public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
return new UnmodifiableMap<>(m);
}
Run Code Online (Sandbox Code Playgroud)
和构造函数代码:
UnmodifiableMap(Map<? extends K, ? extends V> m) {
if (m==null)
throw new NullPointerException();
this.m = m;
}
Run Code Online (Sandbox Code Playgroud)
所以你看到复杂性是O(1).
Map从Collections.unmodifyingMap(Map)返回的将是真实底层映射的瘦代理,其中某些方法被禁用(put等等)。没有理由期望它会获取底层地图的副本。
返回:指定地图的不可修改视图。
但请记住,不可修改的映射只是底层映射的视图,因此底层映射中的更改将反映在不可修改的映射中。因此,这样做是安全的:
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;
}
Run Code Online (Sandbox Code Playgroud)
在复杂性问题上,Sergey Pauk很好地阐述了这一点。