简体   繁体   English

为什么具有相同哈希码的对象不相等

[英]Why can objects with equal hash codes be not equal

I found this sentence in my book: 我在书中发现了这句话:

If hashcodes of two objects are equals, that may not mean that objects are equals. 如果两个对象的哈希码相等,则可能并不意味着对象相等。

Can someone please explain me this sentence? 有人可以给我解释一下这句话吗?

Consider, for example, two objects of the Long class. 例如,考虑Long类的两个对象。 Since hashCode returns an int , and the long (and Long ) type has a larger range than int , this means there must be two Long objects that have the same hashCode even though they are not equal to each other. 由于hashCode返回一个int ,并且long (和Long )类型的范围大于int ,这意味着必须存在两个具有相同hashCode Long对象,即使它们彼此不相等。

答案很简单: hashCode()偶然会为两个完全不同的对象产生相同的数字。

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection. 哈希码是一个数字值,用于在基于哈希的集合中插入和标识对象。

It is a fixed size value so it can't be unique for every existing object so from time to time it suffers collisions. 它是一个固定的大小值,因此它对于每个现有对象都不是唯一的,因此有时会遭受碰撞。 Basically, hashCode() can produce the same value for two different objects. 基本上,hashCode()可以为两个不同的对象产生相同的值。

Example: 例:

    String first = "wh";
    String second = "xI";
    System.out.println(first.equals(second));
    System.out.println(first.hashCode() + " " + second.hashCode());

在基于哈希的实现中,无论何时您检查两个对象的相等性,它都首先检查哈希代码,如果两个对象都相同,则调用equals方法,该方法也返回true,则只有两个对象被视为相等。

2 equal object will have the same hashcode. 2个相等的对象将具有相同的哈希码。

2 objects with the same hascode don't have to be equal. 具有相同hascode的2个对象不必相等。

Lets say the hascode method produces it's value by counten the letters of a name (bad practice, but I'm using this example to explain it), but the equals compares each character: 可以说hascode方法通过计数名称的字母来产生其值(这是不好的做法,但是我正在使用此示例进行解释),但是equals比较每个字符:

Paul and Mary would both return the hascode 4, but the characters are not equal Paul和Mary都将返回hascode 4,但是字符不相等

Even if the hashCode of an object would be the memory address at creation time it still must be stored inside the object header because of the garbage collector. 即使对象的hashCode在创建时就是内存地址,由于垃圾回收器的存在,它仍必须存储在对象标头中。

The garbage collector may freely move objects around to do its work, so the current memory address may change anytime. 垃圾收集器可以自由移动对象以完成其工作,因此当前内存地址可能随时更改。 However: 然而:

the {@code hashCode} method must consistently return the same integer, provided no information used in {@code equals} comparisons on the object is modified. {@code hashCode}方法必须一致地返回相同的整数,前提是未修改该对象的{@code equals}比较中使用的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM