[英]What is the drawback if two same objects have different hashcode
I know that different objects may have same hash code. 我知道不同的对象可能具有相同的哈希码。 But what if equal objects have different hashcode (just a curious question so don't ask me why i do so):
但是,如果相等的对象具有不同的哈希码(只是一个奇怪的问题,所以不要问我为什么这样做):
public class Myclass{
int data = 0;
@Override
public boolean equals(Object obj) {
return obj instanceof Myclass && ((Myclass) obj).data == this.data;
}
@Override
public int hashCode() {
return (int)(Math.random()*1000);
}
}
If you fail to satisfy equals-hashCode contract, then any algorithm or data structure which relies on this contract may work incorrectly. 如果您未能满足equals-hashCode协定,那么依赖于此合同的任何算法或数据结构都可能无法正常工作。 The examples of such data structures are
HashMap
, LinkedHashMap
, ConcurrentHashMap
, Hashtable
(if your object is used as key), HashSet
, LinkedHashSet
. 此类数据结构的示例包括
HashMap
, LinkedHashMap
, ConcurrentHashMap
, Hashtable
(如果您的对象用作键), HashSet
, LinkedHashSet
。
Note that in your case the problem is even worse: you return different hashCode on the same object when hashCode
method is invoked several times. 请注意,在您的情况下问题更严重:当多次调用
hashCode
方法时,您在同一对象上返回不同的hashCode。 So you don't even need two equal objects to break the collection. 所以你甚至不需要两个相同的对象来打破集合。 For example, such code usually prints false (though may occasionally print true):
例如,这样的代码通常打印为false(尽管偶尔可以打印为true):
public static void main(String[] args) {
Myclass m = new Myclass();
Set<Myclass> set = new HashSet<>();
set.add(m);
System.out.println(set.contains(m));
}
What you have in your code is not two equal objects with different hashcode, but an object that will return different hashcode on each invocation of hashcode()
. 您在代码中拥有的不是具有不同哈希码的两个相等对象,而是在每次调用
hashcode()
将返回不同哈希码的对象。
What will happen is that you wont be able to use this class in hashes- since you'll get different hashcode each time, you wont be able to get your object out from the hash, and also everytime you insert into the hash an object, it will be treated as non-existing in the hash 会发生什么事情是你不能在哈希中使用这个类 - 因为你每次都会得到不同的哈希码,你不能从哈希中得到你的对象,并且每次你在哈希中插入一个对象时,它将被视为散列中不存在的
Hashcode is used in datastructures like HashMap or HashSet to determine where a particular object is going to be stored at. Hashcode用于HashMap或HashSet等数据结构中,以确定特定对象的存储位置。 If two objects end up with the same hash code, then it results in a confusion when they are to be stored or retrieved from hash based structures.
如果两个对象以相同的哈希码结束,那么当它们从基于哈希的结构存储或检索时会导致混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.