• Post Reply Bookmark Topic Watch Topic
  • New Topic

hashCode()  RSS feed

 
Jim Baiter
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • 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
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • 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
 
Peter Haggar
author
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!