• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

hashCode()

 
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am overriding equals() in some classes that will be
frequently used so I am looking for the best performing
hashCode() to use? If I have a class with several members,
should I just use the XOR of the hashCode()'s for those
members?
Thanks in advance,
Jim
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Baiter:
I am overriding equals() in some classes that will be
frequently used so I am looking for the best performing
hashCode() to use?


Why do you need hashCode() to implement equals()? I thought you just needed hashCode() if you wanted to stick your objects into a HashMap.

If I have a class with several members,
should I just use the XOR of the hashCode()'s for those
members?


That should usually be quite effective. The only exception I can think of is an aggregate with multiple, identical member objects that each have a limited set of values. That wouldn't work for the same reason XORing the characters in a string won't work.
- Peter
 
author
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Peter den Haan:
Why do you need hashCode() to implement equals()? I thought you just needed hashCode() if you wanted to stick your objects into a HashMap.


You should always override hashCode() if you override equals(). The reason is that if two objects are equal, their hashcodes must be the same. See the doc for hashCode() of the java.lang.Object class.
Peter Haggar
------------------
Senior Software Engineer, IBM
author of: Practical Java
reply
    Bookmark Topic Watch Topic
  • New Topic