The hashCode of a java Hashtable element is always unique?
If not, how can I guarantee that one search will give me the right element?
The hashCode of a java Hashtable element is always unique?
If not, how can I guarantee that one search will give me the right element?
They should. At least within the same class.
By specifying your self a good
hasCode
implementation for your class: Override equals() and hashCodeNot necessarily. Two distinct (and not-equal) objects can have the same hashcode.
From the Java documentation:
So yes, you can typically expect the default
hashCode
for an Object to be unique. However, if the method has been overridden by the class you are storing in theHashtable
, all bets are off.First thing first.
You should consider to use HashMap instead of Hashtable, as the latter is considered obsolete (it enforces implicit synchronization, which is not required most of the time. If you need a synchronized HashMap, it is easily doable)
Now, regarding your question.
Hashcode is not guaranteed to be unique mathematically-wise,
however, when you're using HashMap (or Hashtable), it does not matter.
If two keys generate the same hash code, an equals is automatically invoked on each one of the keys to guarantee that the correct object will be retrieved.
If you're using a String as your key, you're worry free,
But if you're using your own object as the key, you should override the equals and the hashCode methods.
The equals method is mandatory for the proper operation of HashMap, whereas the hashCode method should be coded such that the hash-table will be relatively sparse (otherwise your hashmap, will be just a long array)
If you're using Eclipse there's an easy way to generate hashCode and equals, it basically does all the work for you.
Ideally, yes. In reality, collisions do occasionally happen.