Optimise hashCode() and toString()
Brought to you by:
fgiust
Provide an optimised version of hashCode() and
toString() when the object is immuable (all fields are
declared final).
For example:
public class Person {
private final String firstName;
private final String lastName;
// added by commonClipse
private transient int hashCode = 0;
private transient String toString = null;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return firstName;
}
public int hashCode() {
if (hashCode == 0) {
hashCode = HashCodeBuilder(357504959,
1759723435)
.append(this.firstName)
.append(this.lastName)
.toHashCode();
}
return hashCode;
}
public String toString() {
if (toString == null) {
toString = new ToStringBuilder(this)
.append("firstName", this.firstName)
.append("lastName", this.lastName)
.toString();
}
return toString;
}
}
Logged In: YES
user_id=751436
Originator: NO
I suggest you compute the hashcode and toString value at construction time instead of lazily as shown in the code.
Rationale: immutable object are intrinsically threadsafe, but by having some attributes calculated in a thread-unsafe manner (you can easily have several threads calculating the hashcode or the toString at the same time), you somewhat break this expectation.