gpt4 book ai didi

Java map.copyOf 不使用源映射比较器

转载 作者:行者123 更新时间:2023-12-05 01:03:34 25 4
gpt4 key购买 nike

我有无数带有自定义键和比较器的 map 。我注意到当我使用类似的代码创建 map 时

    var map = TreeMap<>( someCustomComparator );

然后我使用如下代码创建它的不可变(且小而快)副本:

    map = Map.copyOf( map );

然后 map.get(similarObject) 然后无法检索 someObject,即使 someObjectsimilarObject 比较比较器someCustomComparator下的equal(“具有相同的等价类”)。

调试 API 我发现 Map.copyOf 返回一个使用 Object::equals 比较键的映射实现,即它不使用用于比较键的比较器构造原始 map (在我的示例中,这将是 someCustomComparator)。显然当 someObjectsimilarObject 不是同一个对象但在 someCustomComparator 下具有相同的等价类但 Object::equals 没有被覆盖,这会产生奇怪的结果

    map.get( similarObject ) ==> someObject

map = Map.copyOf(map)指令之前,并且

    map.get( similarObject ) ==> null 

map = Map.copyOf(map) 指令之后。这是我必须忍受的预期行为还是应该报告 Java 缺陷?

(请注意,some/similarObject 类也实现了 comparableMap.copyOf 实现也忽略了这一点。)

(我认为这种行为在所有集合 copyOf 实现中都很常见。)

最佳答案

copyOf 的规范方法状态

Returns an unmodifiable Map containing the entries of the given Map.

(强调我的)

这意味着只有条目被复制,没有其他内容。因此,这是预期行为,而不是错误。

另一方面,正如建议的 in the commentsTreeMap 类的构造函数的文档说

Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method runs in linear time.

Parameters:

m - the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map

(再次强调我的)

关于Java map.copyOf 不使用源映射比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74040214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com