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.
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.
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