• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

hashCode algorithm for integers  RSS feed

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:
I need to supply a compareTo() method for a class that contains 2 integers representing a part of a whole (similar to a fraction containing a numerator and denominator. There are other attributes in the class, but equality (and therefore the hascode) is based solely on these 2 integers. What do you think of this algorithm?

The challange is to represent the 2 integers as one int (the return value). It is perfectly fine that 2 sets of integer values (such as 1/3 and 10/30) return the same hashCode. These 2 sets are considered equal.

- Rolf.
 
Ranch Hand
Posts: 1166
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two object can return the same hashCode() value and still not be considered equal. I imagine that there are two pairs of integers that would have the same hash code as you've coded but still shouldn't have compareTo() return 0. Why not just use doubles inside of equals() and compareTo() to determine what boolean or integer to return?

But this seems like a reasonable implementation of hashCode(). Well, what makes a good hashCode()?

- If none of the values involved in equals() change than the value returned by hashCode() must not change. Check.
- If two objects are "equals()", they return the same hashCode(). Check.
- If two object are NOT "equals()", then it would be nice if hashCode returned different values. For the most part, check.

Ryan
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you show us the implementation of equals, please?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!