Answer the question
In order to leave comments, you need to log in
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));
}
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question