hashCode()
is a not generally going to be a bijection, because it's not generally going to be an injective map.
hashCode()
has int
s as its range. There are only 2^32 distinct int
values, so for any object where there there can be more than 2^32 different ones (e.g., think about Long
), you are guaranteed (by the pigeonhole principle that at least two distinct objects will have the same hash code.
The only guarantee that hashCode()
gives you is that if a.equals(b)
, then a.hashCode() == b.hashCode()
. Every object having the same hash code is consistent with this.
You can use the hashCode()
to uniquely identify objects in some very limited circumstances: You must have a particular class in where there are no more than 2^32 possible different instances (i.e., there are at most 2^32 objects of your class which pairwise are such that !a.equals(b)
). In that case, so long as you ensure that whenever !a.equals(b)
and both a
and b
are objects of your class, that a.hashCode() != b.hashCode()
, you will have a bijection between (equivalence classes of) objects and hash codes. (It could be done like this for the Integer
class, for example.)
However, unless you're in this very special case, you should create a unique id some other way.