看着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/