We can keep a member variable to store hashcode for the created object. And we will return that variable whenever, a user asks for hashcodes. Here, in this article, we will use a class which is an immutable class.
In the below class, I use hashcode instance variable to store the hashcode. Hashcode for a given object is calculated only once, in the constructor by calling calculateHashCode method.
And we return the same values whenever hashCode() function is called.
package com.immutables;
public class HowToCacheHashcodes {
private final int hashcode;
private final String fName;
private final String lName;
public HowToCacheHashcodes(final String fName, final String lName) {
this.fName = fName;
this.lName = lName;
hashcode = calculateHashCode(fName, lName);
}
private int calculateHashCode(String fName, String lName) {
return fName.hashCode() + lName.hashCode();
}
@Override
public int hashCode() {
return hashcode;
}
@Override
public boolean equals(Object other) {
if(other != null && other instanceof HowToCacheHashcodes) {
if(other == this) return true;
HowToCacheHashcodes otherObject = (HowToCacheHashcodes) other;
return this.lName.equals(otherObject.lName) && this.fName.equals(otherObject.fName);
}
return false;
}
}