0

Here is a code:

Object o = new Object();
System.out.println(o.hashCode());
System.out.println(System.identityHashCode(o));

The output is similar in both syso so I want to ask if there any use case of System#identityHashCode except using it as method reference? The reason why I am concerned about it is because java has similar pattern methods in it.

  • [The javadoc](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#identityHashCode-java.lang.Object-) answers your question. In case you have trouble understanding it : it disregards the class' hashcode implementation and use the default one instead. – Aaron Jul 01 '20 at 10:38
  • Lots of classes override `hashCode()` to be compatible with value-based equality. So if you have a use-case where you want a hashcode more consistent with identity-based equality, you might use `System.identityHashCode` – khelwood Jul 01 '20 at 10:39
  • @khelwood So it means that `o.hashCode()` and `System.identityHashCode(o)` might return different values in some circumstances right? –  Jul 01 '20 at 10:41
  • Yes, if `o` was a member of some other class, not a `new Object()`. – khelwood Jul 01 '20 at 10:41
  • @khelwood Got it. Thanks –  Jul 01 '20 at 10:42
  • Here's an example : https://ideone.com/Ag3V8T – Aaron Jul 01 '20 at 10:43
  • Thanks @Aaron, that's very helpful in visualizing it :) –  Jul 01 '20 at 10:45

0 Answers0