when would be a reasonable time to do line #4 instead of line #3? Or are they perfectly redundant invokes?
1 Object o1 = new Object();
2
3 int hcObj = o1.hashCode();
4 int hcSys = System.identityHashCode(o1);
Sometimes you might want to create a set of distinguishable objects. Some of those objects may be equal to each other, but you still want references to all of them... only throwing away genuinely duplicate references. You might do that because the equals
implementation isn't the one you're interested in (some classes override equals
when you really don't want them to) or because you're actually just trying to count separate instances etc.
To do that efficiently (i.e. backed by a hash table of some kind) you want a hash code based on identity rather than equality - which is exactly what identityHashCode
gives you. It's rarely useful, but it can still be handy at times.
For a plain Object
, yes, it's redundant. But there are cases where a class might want to use the default hashCode
implementation (based on reference equality) on an instance of a type that could have overridden hashCode
.
Grepcode lists these call sites, namely including IdentityHashMap
amongst others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With