Java's System.identityHashCode()
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().
That hash code is based on the object identity, so it will always be the same for the same object, no matter if the object is mutated between calls to identityHashCode().
In addition to that, there will not be hash collisions between any two living objects (with some Java runtimes): (the former is an inaccurate statement by Oracle in the source given below, as Jai's answer shows, and as another bug report points out as well - which basically invalidates my original question...)
[...] garbage objects are readily reclaimed and the address space is reused. The collisons result from address space reuse. If the original object remains live (not GCed) then you will not encounter this problem.
In .Net, there is RuntimeHelpers.GetHashCode(), which fulfills the first condition, but not the second:
Note that GetHashCode always returns identical hash codes for equal object references. However, the reverse is not true: equal hash codes do not indicate equal object references. A particular hash code value is not unique to a particular object reference; different object references can generate identical hash codes.
So is there anything like Java's identityHashCode() in .Net?
Edit:
It was suggested that this is the same as Memory address of an object in C# which it is not, as the memory address cannot be used here (solely), as memory management moves objects around, hence the address may change during the lifetime of an object.
I am trying to build a stable sort algorithm.statement I added to your post? It really gave useful context to your problem.In addition to that, there will not be hash collisions between any two living objects.Object#hashCode()andSystem.identifyHashCode()guarantees that the value it returns for a particular instance would never change, it does not mention that it would return a unique value for each object. In fact, it only returns the trailing 32-bit memory address in the heap of the object - this means that0x 0 FFFF FFFFand0x 1 FFFF FFFFwould both return0x FFFF FFFF. You can modify the bug report's example, such that you make a static list to store theobjto prevent GC, collision will still occur.