Collections.unmodifiableMap 性能很重要吗?

Is Collections.unmodifiableMap performance critical?

我有一个 hashmap<String, String>,其中包含大约一千个条目。 现在我必须以无法在 class 之外修改的方式公开它。所以我写成

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

此方法调用非常频繁。我的问题是
1。这会导致性能问题吗?
2.Is 方法 (unmodifiableMap) 遍历 Map 或者这将以 O(constant) 复杂度执行其 activity?

Collections.unmodifiableMap(Map) 返回的 Map 将是禁用某些方法(put 等)的真实底层地图的瘦代理。没有理由期望它会复制底层地图。

Returns: an unmodifiable view of the specified map.

但是请记住,不可修改的地图只是基础地图的 视图,因此基础地图中的更改将反映在不可修改的地图中。因此这样做是安全的:

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;
}

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

这是一个非常精简的实现:

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)