Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use of System.identityHashCode(obj) - when? why?

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);
like image 660
LRI CS Avatar asked Jun 14 '13 17:06

LRI CS


2 Answers

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.

like image 135
Jon Skeet Avatar answered Oct 23 '22 15:10

Jon Skeet


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.

like image 41
Paul Bellora Avatar answered Oct 23 '22 15:10

Paul Bellora