If one does not override the hashCode
method, what is the default implementation of hashCode
?

- 15,593
- 27
- 93
- 149
-
About default implementation you can read [this](http://blogs.tedneward.com/CommentView,guid,eca26c5e-307c-4b7c-931b-2eaf5b176e98.aspx) – CAMOBAP Feb 28 '13 at 08:39
-
1default implementation is JVM specific, but in general it returns `return Objects.hash(this.field1, this.field2, this.field3, etc.);` – NoName Jun 24 '17 at 06:19
3 Answers
Then this class inherits hashCode
from one of its ancestors. If non of them overrides it, then Object.hashCode is used.
From the docs:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (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.)
So default implementation is JVM-specific

- 218,210
- 55
- 464
- 476

- 13,035
- 13
- 56
- 62
-
Thank you, yes. What does the implementation of `Object.hashCode() look` like? – John Threepwood Feb 28 '13 at 08:29
-
1@JohnThreepwood it's an implementation detail, you need to address your JVM docs for that. – default locale Feb 28 '13 at 08:32
-
3
By default, methods that are not overriden are inherited from Object
.
If you look at that method's documentation, the return values are "[...] distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer [...])
". The method in java.lang.Object
is declared as native, which means the implementation is provided by the JVM and may vary depending on your runtime environment.
A small example:
Object o1 = new Object();
Object o2 = new Object();
System.out.println(o1.hashCode());
System.out.println(o2.hashCode());
prints (using my jdk6):
1660187542
516992923
A Hex representation of the hashCode()
value is used in the default implementation of toString()
by the way: Running System.out.println(o1)
prints something like
java.lang.Object@7a5e1077

- 11,489
- 3
- 25
- 51
Object.hashcode() is a native method.
public native int hashCode();
That means it's implemented in platform specific code and is exposed as a native method.
code for the same will be a compiled code and not available withing JDK
this existing question might provide more info.

- 1
- 1

- 15,480
- 4
- 33
- 57