gpt4 book ai didi

java - java.util.HashMap.containsKey(Object key) 实现是否违反 java.util.Map.containsKey(Object key) 文档?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:57:34 28 4
gpt4 key购买 nike

java.util.Map.containsKey(Object key)文件说: @throws ClassCastException if the key is of an inappropriate type for this map .

java.util.HashMap.containsKey(Object key)实现没有说明任何事情。

我的问题:

如果我创建一个 Map<String,String> map = new HashMap<>();并调用 containsKey使用 Integer 的方法该值被散列(作为 String )但该方法不会抛出 Exception .

顺便说一句,4 的哈希值与“4”的哈希值不同。

这真的是预期的行为吗?

最佳答案

这似乎是一个可选的限制,没有应用于HashMap

API 中所述对于 containsKey:

[...]

Throws:ClassCastException - if the key is of an inappropriate type for this map (optional)

注意“可选”,并查看链接 documentation :

Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the collection may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

关于java - java.util.HashMap.containsKey(Object key) 实现是否违反 java.util.Map.containsKey(Object key) 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49675813/

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