views:

134

answers:

3

The method System.identityHashCode(...) is called that way, because it identifies objects, so two distinct objects can't have same identity-hashcode, right?

It returns an int. But what happens, on a system with huge amount of RAM, when the number of objects exceeds the integer range 2^32?

Wouldn't it be a problem for HashMaps and HashSets when operating on classes which don't override equals and hashCode?

EDIT:
If int is not enough, can I get some real unique ID for an object?

+5  A: 

No, it would just be a normal hash collision. Two unequal objects are allowed to return the same hash - it's just that then both of them will need to be compared for equality.

This isn't restricted to identity hashcodes - consider String.hashCode(). Obviously there are more possible strings than int values, so there must be at least one hash value which is the result of hashing multiple strings. A HashMap/HashSet would first take the hash code to quickly narrow down the set of possible matches to only those entries which have the same hash code, and then call equals() on each one in turn until it found a match or determined that none of the entries was equal to the given key.

Jon Skeet
Thanks! Is there a Java method to get some really unique ID of an object? I mean, the JVM can and must be able to do this, so why not the developer?
java.is.for.desktop
@java: Not that I'm aware of. The appropriate type would depend on the JVM in question, *and* that ID might change over time as it was moved around in memory by the GC.
Jon Skeet
@Jonik: Suppose you want to have a hash map which only considers object identity, and not normal equality - you wanted to store separate but equal strings separately, for example. You need to be able to test for object identity - that's easy via == - but you also need to be able to get an appropriate hash code. How would you do that without identityHashCode?
Jon Skeet
@Jonik: I think it's reasonably clear. It's basically saying, "if you were able to make a non-virtual call to `Object.hashCode()` for this object, what would it return?"
Jon Skeet
+3  A: 

Wrong. Any number of objects can have the same identityHashCode.

EJP
Additional: The only guarentee is that two objects with different identityHashCodes are not the same object.
Peter Lawrey
+2  A: 

"can I get some real unique ID for an object?" I would ask you what would you do with such an id? Does it need to be unique at a given instant, over the life of the JVM, or globally across any number of systems?

You could generate a UUID for each object you want a unique id for. However, duplicate ids are still theoretically possible, just highly unlikely.

Peter Lawrey
To put highly unlikely in perspective: The chance of getting 1 duplicate ID when generating tens of trillions of them is as large as getting hit by a meteorite in a year (source: Wikipedia)
Bart van Heukelom