M
Marco
In my NamedBitField class I define equals() to mean that 2
NamedBitFields are equal if all 3 of their fields are equal.
Any suggestions for improving my hashCode() definition? I
can improve its performance by caching the computed hashCode
in a transient field, sure, but can I improve the _way_ it's
computed?
class NamedBitField {
String name; // name of bit field
int startIndex; // where it starts
int length; // how many bits it occupies
pubic boolean equals(Object obj) {
if (this == obj)
return true;
if ( obj == null || this.getClass() != obj.getClass() )
return false;
NamedBitField other = (NamedBitField) obj;
return
this.name.equals(other.name) &&
this.startIndex == other.startIndex &&
this.length == other.length;
}
public int hashCode() {
// to make this symmetric with equals() I'd prefer to
// involve all 3 fields (name, startIndex and length)
// in the computation of the hash. But how?
//
// Here I'm simply reusing String.hashCode(), but the
// hashed String at least incorporates the other
// fields
return ((name + startIndex) + length).hashCode();
}
}
Marco
NamedBitFields are equal if all 3 of their fields are equal.
Any suggestions for improving my hashCode() definition? I
can improve its performance by caching the computed hashCode
in a transient field, sure, but can I improve the _way_ it's
computed?
class NamedBitField {
String name; // name of bit field
int startIndex; // where it starts
int length; // how many bits it occupies
pubic boolean equals(Object obj) {
if (this == obj)
return true;
if ( obj == null || this.getClass() != obj.getClass() )
return false;
NamedBitField other = (NamedBitField) obj;
return
this.name.equals(other.name) &&
this.startIndex == other.startIndex &&
this.length == other.length;
}
public int hashCode() {
// to make this symmetric with equals() I'd prefer to
// involve all 3 fields (name, startIndex and length)
// in the computation of the hash. But how?
//
// Here I'm simply reusing String.hashCode(), but the
// hashed String at least incorporates the other
// fields
return ((name + startIndex) + length).hashCode();
}
}
Marco