Donate Share

commonclipse

Tracker: Feature Requests

5 Optimise hashCode() and toString() - ID: 1016175
Last Update: Comment added ( ddossot )


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;
}
}


Ludovic Claude ( ludovicc ) - 2004-08-25 17:51

5

Open

None

Nobody/Anonymous

None

None

Public


Comment ( 1 )




Date: 2007-04-13 19:30
Sender: ddossot


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.



Log in to comment.

Attached File

No Files Currently Attached

Change

No changes have been made to this artifact.