Se si esegue quanto segue su HotSpot Java 7 versione a 64 bit.C'è una ragione per cui Object.hashCode() è a 31 bit?
int countTopBit = 0, countLowestBit = 0;
for (int i = 0; i < 100000000; i++) {
int h = new Object().hashCode();
if (h < 0)
countTopBit++;
if ((h & 1) == 1)
countLowestBit++;
}
System.out.println("The count of negative hashCodes was " + countTopBit + ", the count of odd hashCodes was " + countLowestBit);
si può ottenere un risultato come
The count of negative hashCodes was 0, the count of odd hashCodes was 49994232
mi chiedevo se questo significa che il Object.hashCode()
è veramente solo 31-bit e il motivo per cui questo potrebbe essere così?
Non è il caso che il bit superiore non sia utilizzato. Dalla sorgente per HashMap
257 /**
258 * Applies a supplemental hash function to a given hashCode, which
259 * defends against poor quality hash functions. This is critical
260 * because HashMap uses power-of-two length hash tables, that
261 * otherwise encounter collisions for hashCodes that do not differ
262 * in lower bits. Note: Null keys always map to hash 0, thus index 0.
263 */
264 static int hash(int h) {
265 // This function ensures that hashCodes that differ only by
266 // constant multiples at each bit position have a bounded
267 // number of collisions (approximately 8 at default load factor).
268 h ^= (h >>> 20)^(h >>> 12);
269 return h^(h >>> 7)^(h >>> 4);
270 }
Questo potrebbe essere un'ottimizzazione. Le tabelle hash prendono spesso il codice hash mod il numero di bucket, ma devono prima mascherare il primo bit per evitare un indice negativo. Forse questo è per evitare quel passo dopo? – templatetypedef
@templatetypedef Mi sono chiesto se questo potrebbe essere il caso, ma ho il sospetto che Object.hashCode() non sia usato negli insiemi di hash che spesso è sovrascritto da hashCode() a 32 bit. Anche HashMap muta il hashCode raw in modo che venga usato il bit più in alto. –
@templatetypedef: ma per quanto riguarda le sostituzioni dell'utente che non lo fanno? La tabella hash deve ancora occuparsi di questo codice –