Skip to content

Instantly share code, notes, and snippets.

@RealDeanZhao
Created March 28, 2017 13:52
Show Gist options
  • Save RealDeanZhao/97162f2e0c3df2a5ffc472b674c55f07 to your computer and use it in GitHub Desktop.
Save RealDeanZhao/97162f2e0c3df2a5ffc472b674c55f07 to your computer and use it in GitHub Desktop.
JAVA Lazily initialized, cached hashCode

If a class is immutable and the cost of computing the hash code is significant, you might consider caching the hash code in the object rather than recalculating it each time it is requested. If you believe that most objects of this type will be used as hash keys, then you should calculate the hash code when the instance is created. Otherwise, you might choose to lazily initialize it the first time hashCode is invoked (Item 71).

// Lazily initialized, cached hashCode
private volatile int hashCode;  // (See Item 71)
@Override public int hashCode() {
       int result = hashCode;
       if (result == 0) {
           result = 17;
           result = 31 * result + areaCode;
           result = 31 * result + prefix;
           result = 31 * result + lineNumber;
           hashCode = result;
       }
       return result;
}
@RealDeanZhao
Copy link
Author

immutable!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment