Search code examples
javatupleshashcode

ImmutablePair Hashcode


I need to use an ImmutablePair. But it seems that its hashcode is defined as this: https://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/tuple/Pair.html#line.208. Which means ImmutablePair.of("a", "a") and ImmutablePair.of("b", "b") will have the same hashCode 0:

ImmutablePair<String, String> p1 = ImmutablePair.of("a", "a");
System.out.println("Pair 1 hashcode: " + p1.hashCode());
ImmutablePair<String, String> p2 = ImmutablePair.of("b", "b");
System.out.println("Pair 2 hashcode: " + p2.hashCode());

Out put:

Pair 1 hashcode: 0
Pair 2 hashcode: 0

This seems very strange to me. Can someone explain what is the rational of doing this?


Solution

  • As specified in the comment on the method definition, this implementation is required by the contract of Map.Entry, which ImmutablePair implements.