I remember eclipse and idea have this template to automatically create an object\'s hashCode based on its attributes.
One of the strategies if a number and a string is u
A hashcode method is something that potentially be called many times, and is therefore worth optimizing. If the calculation is complicated, consider memoizing the hash value. Also, avoid doing things that entail more calculation than is necessary. (For example, the StringBuilder solution spends most of its time creating the temporary String.)
The other thing I want to point out is that the quality of the hash is important. You want to avoid any hashcode algorithm that maps lots of common keys. If that happens, hash table lookup may no longer be O(1). (In the worst case it will be O(N) ... i.e. equivalent to a linear search!). Here's an example of a bad hash function:
int hashcode() {
int hash = 1;
for (int val : this.values) {
hash = hash * value;
}
return hash;
}
Consider what happens if an element of this.values
is zero ...