Java:La méthode hashCode()
De WIKI.minetti.org
But
La méthode hashCode() permet d'optimiser l'utilisation de la méthode equals() en regroupant les instances entre-elles. Ainsi, les instances d'un même groupe auront le même code de hash.
Contraintes
L'algorithme de calcul de la valeur de hash doit obéir à certaines contraintes:
- Les groupes doivent avoir à peu près le même nombre d'instances.
Algorithme pour les types primitifs
| Type | Algorithme |
|---|---|
| boolean | return x ? 0x55555555 : 0x27777777; |
| byte | int h = x & 0x7F;
return h | (h << 8) | (h << 16) | (h << 24); |
| char | (x << 16); |
| short | int h = x & 0x7FFF:
return h | (h << 16); |
| int | return x; |
| long | return (int)(x ^ (int)(x >> 32)); |
| float | return Float.floatToIntBits(x); |
| double | Long l = Double.doubleToLongBits(x);
return (int)(l ^ (int)(l >> 32)); |
Combinaison d'attributs
Entre 2 attributs, hash1 et hash2, de type int:
int hash = 0
int h = hash1;
for (int i = 7; i >= 0; --i) {
if (i == 4) {
h = hash2;
}
hash = hash * 21 + (char)h;
h >>>= 8;
}