简体   繁体   中英

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. 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()偶然会为两个完全不同的对象产生相同的数字。

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.

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 objects with the same hascode don't have to be equal.

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:

Paul and Mary would both return the hascode 4, but the characters are not equal

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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