Collections.unmodifiableMap性能是否至关重要?

时间:2015-03-20 08:55:50

标签: java collections hashmap

我有一个hashmap<String, String>,其中包含大约一千个条目。 现在我必须以不能在课外修改的方式公开它。所以我写了像

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

此方法被非常频繁地调用。我的问题是1。这会导致性能问题吗?
2.Is方法(unmodifiableMap)迭代Map还是会以O(常数)复杂度执行它的活动?

2 个答案:

答案 0 :(得分:7)

这是一个非常薄的实现:

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

和构造函数代码:

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

因此,您看到复杂性 O(1)

答案 1 :(得分:4)

Collections.unmodifiableMap(Map)返回的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;
}

关于复杂性问题Sergey Pauk很好地涵盖了这一点。

相关问题