-1

The hashCode() method return a serie of numbers, but two different objects can have the same result. So how this function is really calculating that value,internally ? Is that related to memory case, and what's the element included in th calculation?

Meher_Ay
  • 31
  • 1
  • 5
  • 2
    The identity hash code (i.e. the value returned by `Object.hashCode()` and by other classes that don't override that method and provide their own implementation) is implementation specific and what exactly it is depends on the JVM implementation. – Joachim Sauer Oct 07 '19 at 15:20

1 Answers1

0

According to the Object javadoc, hashCode method may returns the object's address in memory at some point in time

The hashCode may or may not be implemented as some function of an object's memory address at some point in time

https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#hashCode()

Remember that this method is useful to compare whether two or more or object are the same together with equals method,but you can override this method to return the same hashcode if some attributes (e.g PKs) are the same although them are different objects in memory

imperezivan
  • 761
  • 5
  • 13
  • The Javadoc you link to is for the obsolete Java 6 version. Even that one says "This is typically implemented by converting the internal address of the object into an integer, **but this implementation technique is not required by the JavaTM programming language**." This sentence is removed in later versions. It is wrong to say "hashCode returns the object's address in memory." In fact, the garbage collector can reallocate an object to a different address yet its hashCode will remain the same. You shouldn't use hashCode to check if two objects are the same - do `if (obj1 == obj2)` instead. – DodgyCodeException Oct 07 '19 at 16:36
  • `if (obj1 == obj2)` works only if you care if the objects are in fact the same physical object. If you want logical equality you need to use `o1.equals(o2)`. These objects may not be the same object, but might be logically equal (e.g. String, Number, etc). – PaulProgrammer Oct 07 '19 at 16:57