java - 为什么 Collections.unmodifiableMap 不检查传递的 map 是否已经是 UnmodifiableMap?

标签 java performance

看着java.util.Collections.unmodifiableMap实现(OpenJDK 11):

    /**
     * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
     * specified map. Query operations on the returned map "read through"
     * to the specified map, and attempts to modify the returned
     * map, whether direct or via its collection views, result in an
     * {@code UnsupportedOperationException}.<p>
     *
     * The returned map will be serializable if the specified map
     * is serializable.
     *
     * @param <K> the class of the map keys
     * @param <V> the class of the map values
     * @param  m the map for which an unmodifiable view is to be returned.
     * @return an unmodifiable view of the specified map.
     */
    public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
        return new UnmodifiableMap<>(m);
    }

我的问题是为什么实现不检查通过的 map 可能已经是UnmodifiableMap ,像这样:
    public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
        if(m instanceof UnmodifiableMap){
            return m;
        }
        return new UnmodifiableMap<>(m);
    }

相反,这个问题可以扩展到所有其他不可修改的集合,一个简单的检查有助于避免 unwanted stackoverflow errors以及不必要的包装。

我想知道是否有理由不这样做?

此外,用户也不太可能(不使用反射/类加载器魔法)以 UnmodifiableMap 进行检查。是私有(private)的。

最佳答案

我总是觉得这也有点奇怪,事实上,当你用 Java 9 或更高版本做几乎相同的逻辑事情时,通过:

    Map<String, Integer> left = Map.of("one", 1);
    Map<String, Integer> right = Map.copyOf(left);
    System.out.println(left == right); // true
你可以看到实现会检查这是否 Map已知是不可变的:
static <K, V> Map<K, V> copyOf(Map<? extends K, ? extends V> map) {
    if (map instanceof ImmutableCollections.AbstractImmutableMap) {
        return (Map<K,V>)map;
    } else {
        return (Map<K,V>)Map.ofEntries(map.entrySet().toArray(new Entry[0]));
    }
}

关于java - 为什么 Collections.unmodifiableMap 不检查传递的 map 是否已经是 UnmodifiableMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59517676/

相关文章:

performance - YCSB 理解输出

Windows 计时器分辨率 vs 应用程序优先级 vs 处理器调度

java - 可执行 Jars 运行非常缓慢

java - 如何使用spring mvc将json反序列化为复杂对象?

java - Android OCR 超正方体 : using data from Pixa objects to display bounding boxes

java - 如何使用Java中的嵌套循环仅打印一次单个数字?

angular - 在 Angular 应用程序中使用静态 HTML 登陆页面

c# - 使用内联对象方法调用与声明新变量

java - FileInputStream 和 ByteArrayInputStream 的区别

SQL Server 2008 分区表和并行性