Can I assume that two objects with the same System.identityHashCode are the same?

Although two different objects may have the same hash code, however, System.identityHashCode() seems to return a pointer to the object's memory. I assume that there can be no exception in 32-bit JVM implementations, including Sun JDK, Open JDK. However, I did not check the source code. In practice, can I assume that two objects with the same System.identityHashCode() same?

+4
source share
3 answers

The short answer is no.

According to the documentation , System.identityHashCode(Object) ...

Returns the same hash code for this object, which will be returned by the hashCode () method by default, regardless of whether or not this class of the hashCode () object overrides.

So let's see the documentation of Object.hashCode() ...

As reasonably practical, the hashCode method defined by the Object class returns different integers for different objects. (This is usually done by converting the internal address of the object to an integer, but this implementation method is not required by the Java programming language .)

+3
source

The answer is no.

System.identityHashCode () just return Object.hashCode () .

Returns the same hash code for this object, which will be returned by the hashCode () method by default, regardless of whether the given object class overrides hashCode (). The hash code for the null reference is null.

So far for Object.hashCode()

As far as reasonably practical, the hashCode method defined by class Object returns different integers for different objects. (This is usually implemented by converting the internal address of the object to an integer, but this implementation technique is not required by the JavaTM programming language.)

However, there is a bug in the Sun JDK indicating that two objects can return the same hash code.

+6
source

There are only two things in your question.

First, that returns System.identityHashCode (Object).

Returns the same hash code for this object, which will be returned by the hashCode () method by default, regardless of whether the given object class overrides hashCode (). The hash code for the null reference is zero.

Secondly, what is a hashcode rule when comparing the equality of two objects.

The contract says that if two objects are equal using the equals (object) method, then they must have the same hash code, but if two objects have the same hash code, they are not necessarily equal.

+1
source

Source: https://habr.com/ru/post/1413086/


All Articles