File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes hashCode algorithm for integers Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "hashCode algorithm for integers" Watch "hashCode algorithm for integers" New topic
Author

hashCode algorithm for integers

Rolf Johansson
Ranch Hand

Joined: Feb 25, 2004
Posts: 32
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.
Ryan McGuire
Ranch Hand

Joined: Feb 18, 2005
Posts: 945
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
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Can you show us the implementation of equals, please?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashCode algorithm for integers
 
Similar Threads
Wrong output
can object has multiple values
Fractions
Adding instances of a class
null pointer exception