How to decide hashcode value? Recently I faced an interview question that "Is 17 a valid hashcode?". Is there any mechanism to define hashcode value? or we can give any number for hashcode value?
- 1Related: javamex.com/tutorials/collections/…Luiggi Mendoza– Luiggi Mendoza2013-02-25 06:51:18 +00:00Commented Feb 25, 2013 at 6:51
- It very well could be - all depends on how hash function was definedmvp– mvp2013-02-25 06:52:26 +00:00Commented Feb 25, 2013 at 6:52
- 1Another resources: stackoverflow.com/q/2738886/1065197 stackoverflow.com/q/113511/1065197 ... you can find lot of this on the net.Luiggi Mendoza– Luiggi Mendoza2013-02-25 06:53:02 +00:00Commented Feb 25, 2013 at 6:53
- My answer would be to point out that new Integer(17) creates an object whose hashcode is 17. Anything that uses hashing in Java has to treat 17, or any other int, as a valid hashcode.Patricia Shanahan– Patricia Shanahan2013-02-25 07:00:40 +00:00Commented Feb 25, 2013 at 7:00
- so, any possitive integer is valid hash code? or we should sum up the unicode for chars and calculate?samuelebe– samuelebe2013-02-25 07:07:10 +00:00Commented Feb 25, 2013 at 7:07
3 Answers
Hashcodes should have good dispersion, so that different objects will be saved in different positions of the hash table (otherwise performance could be degraded).
From that point, while 17 us a "valid" hash code (in the sense that it is a 32-bit signed integer), it is suspicious how the hash function was defined.
For instance, a naive approach for hashing a string is just adding the value of each character. This result in similar hash values for simple strings (such as "tar" and "rat" that sum up to the same value).
A common trick is multiplying each value by a small prime, so that simple inputs will return different values, e.g.;
int result = 1; result = 31 * result + a; result = 31 * result + b; or
int h=0; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } (the latter, from the JRE implementation of String.hashCode)
6 Comments
return 0is a "valid" implementation of hashCode (albeit a terrible one).int value, but it's not valid because it doesn't fulfill the rules for a valid equals and hashCode implementation. This is explained in Object#hashCode javadoc and the explanation with a sample hereYa 17 is valid. Usually prime numbers like shown in the link are used, you can implement hashcode using the id of that entity which is a primary key
public int hashCode() { int result = 17; result = 37 * result + (getId() == null ? 0 : this.getId().hashCode()); return result; } this provides different ways for implementing the hascode