W
W
WTFAYD2016-10-30 21:04:02
Java
WTFAYD, 2016-10-30 21:04:02

How are hashcode() and compareTo() related?

class TwoTuple28<A,B> implements Comparable {
  // ...
  public int hashCode() {
    int result = 17;
    result = result * 37 + first.hashCode();
    result = result * 37 + second.hashCode();
    return result;
  }
  public int compareTo(Object o) {
    if(!(o instanceof TwoTuple28)) throw new ClassCastException();
    TwoTuple28 t = (TwoTuple28)o;
    return (this.hashCode() - t.hashCode() < 0) ? -1 : 
    ((this.hashCode() - t.hashCode() > 0 ? 1 : 0));
}

Can you please tell me what is the point of using hashCode() in compareTo()? In compareTo(), we compare the contents of the object, hashCode() of course converts the object's information into a hash code, but is there any exact ratio between different hashCode() that they could be used in compareTo()?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2016-10-31
@zolt85

In the case of compareTo(), we do not just compare two objects, we also give them a "weight" (more, less), so, I think, it is not entirely correct to use the results of hashCode in calculating this "weight". Although if the author is satisfied with everything, and, for example, collections of such objects are sorted exactly as he intended, then I don’t see any problems with this. The main thing is to cover everything with tests.

T
Tiberal, 2016-10-30
@Tiberal

no. due to a collision, there may be an incorrect comparison.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question