0

When I look at "old" version of Android Pair's hashCode, its implementation is following text in

Josh Bloch's Effective Java - Best implementation for hashCode method

"Old" Pair.java

/**
 * Compute a hash code using the hash codes of the underlying objects
 * @return a hashcode of the Pair
 */
public int hashCode() {
    int result = 17;
    result = 31 * result + first.hashCode();
    result = 31 * result + second.hashCode();
    return result;
}

However, when I look at "latest" version of Android Pair's hashCode, it looks like this

"New" Pair.java

/**
 * Compute a hash code using the hash codes of the underlying objects
 *
 * @return a hashcode of the Pair
 */
@Override
public int hashCode() {
    return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
}

May I know, is there any reference source, on why XOR operator is being used? I thought we shouldn't violate Josh Bloch's teaching :) ?

Community
  • 1
  • 1
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

0

It's not clear why the author moved from the prime number technique to the XOR technique, but the change was motivated by needing to support null values in the Pair class. See this commit: https://github.com/android/platform_frameworks_base/commit/162fabbcf81157fddab1c38de09bdabaff8c068a#diff-e73c0c4c169861c96264276ecce62169. In theory, the implementation could have used the old version if neither object is null but if either is, then the hashCode becomes that of the non-null component of the pair (or 0 if both are null).

scorpiodawg
  • 5,612
  • 3
  • 42
  • 62