为什么Java使用'equals'代替'=='来检查对象在Map中的存在? [英] Why Java uses 'equals' instead of '==' to check an object's presence in a Map?
问题描述
假设我想将一个键及其值放在Map中。
Suppose if I want to put a key and its value in a Map.
我相信这就是Java的作用:
I believe it is what Java does:
-
获取密钥的哈希码并检查地图中是否存在具有相同哈希码的密钥。
Get the Hashcode of the key and check whether there is a key in the map with the same hashcode.
如果没有具有相同Hashcode的密钥,则可以将密钥放入Map。
If there is no key with the same Hashcode then the key can be put into Map.
如果有一个具有相同Hashcode的密钥,则使用equals来确定密钥是否可以放入Map。
If there is a key with the same Hashcode then use equals to determine whether the key can be put into Map or not.
我的问题是为什么不使用 ==
而不是等于
在这个过程中?
My question is why not use ==
instead of equals
in this process?
推荐答案
做你的建议会破坏<$ c $的整个概念c>等于 / hashCode
tandem。 等于
和 hashCode
都会变得无用,甚至不应该存在。
Doing what you suggest would break the entire concept of equals
/hashCode
tandem. Both equals
and hashCode
would be rendered useless and should not even exist.
Java允许程序员为他的类定义相等集;如果他不想这样做,他可以选择退出覆盖等于
和 hashCode
—并结束准确地说出你提出的语义。
Java allows the programmer to define the equality sets for his class; if he doesn't want to do it, he can simply opt out of overriding equals
and hashCode
—and end up with exactly the semantics you propose.
举一个具体的例子,根据你的提议,这将在地图中创建两个单独的条目:
To give a specific example, under your proposal, this would create two separate entries in the map:
Map<Integer, String> map = new HashMap<>();
map.put(10_000, "a");
map.put(10_000, "a");
这是因为文字10_000每次都会自动装入 Integer
,根据您的语义,它是两个单独的键。然后,语句
That is because the literal 10_000 will be autoboxed each time into a new instance of Integer
, which, under your semantics, are two separate keys. And then, the statement
System.out.println(map.get(10_000));
将打印 null
,因为你当然正在使用第三个键来获取。事实上,按键检索任何地图值都是不可能的。
would print null
, because of course you are using a third key to get. It would in fact be impossible to retrieve any map value by key.
这篇关于为什么Java使用'equals'代替'=='来检查对象在Map中的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!