java - Best implementation for hashCode method -


how decide on best implementation of hashcode() method collection (assuming equals method has been overridden correctly) ?

the best implementation? hard question because depends on usage pattern.

a cases reasonable implementation proposed in josh bloch's effective java in item 8. best thing there because author explains there why approach good.

a short version

  1. create int result , assign non-zero value.

  2. for every field f tested in equals() method, calculate hash code c by:

    • if field f boolean: calculate (f ? 0 : 1);
    • if field f byte, char, short or int: calculate (int)f;
    • if field f long: calculate (int)(f ^ (f >>> 32));
    • if field f float: calculate float.floattointbits(f);
    • if field f double: calculate double.doubletolongbits(f) , handle return value every long value;
    • if field f object: use result of hashcode() method or 0 if f == null;
    • if field f array: see every field separate element , calculate hash value in recursive fashion , combine values described next.
  3. combine hash value c result:

    result = 37 * result + c 
  4. return result

this should result in proper distribution of hash values use situations.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -