java.is.for.desktop
java.is.for.desktop

Reputation: 11216

What happens to identity-hashcode when there are more objects than `int` can hold?

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?

Upvotes: 2

Views: 1009

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533530

"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.

Upvotes: 2

user207421
user207421

Reputation: 310957

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500893

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.

Upvotes: 7

Related Questions