tags:

views:

50

answers:

3

Hi There,

Edit: Prepare my objects for the use within a HashMap.

after reading a bit about how to generate a hash code, im kind of confused now. My (probably trivial) question is, how should I implement a hashCode method when I have one field that I could use? Can I use the fiels directly? IIUC the values for hashCode must not change during the lifetime of an object, and I only have an ID filed that fits this, but I have read otherwhere, that one should not use ID...despide of that, how would a hashCode function based on this one (unique and not changing) value look like? The equals method is also based on the id only..

Regards

+4  A: 

If your object is mutable, then it is acceptable to have its hash code change over time. Of course, you should prefer immutable objects (Effective Java 2nd Edition, Item 15: Minimize mutability).

Here's the hashcode recipe from Josh Bloch, from Effective Java 2nd Edition, Item 9: Always override hashCode when you override equals:

Effective Java 2nd Edition hash code recipe

  • Store some constant nonzero value, say 17, in an int variable called result.
  • Compute an int hashcode c for each field:
    • If the field is a boolean, compute (f ? 1 : 0)
    • If the field is a byte, char, short, int, compute (int) f
    • If the field is a long, compute (int) (f ^ (f >>> 32))
    • If the field is a float, compute Float.floatToIntBits(f)
    • If the field is a double, compute Double.doubleToLongBits(f), then hash the resulting long as in above.
    • If the field is an object reference and this class's equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If the value of the field is null, return 0.
    • If the field is an array, treat it as if each element is a separate field. If every element in an array field is significant, you can use one of the Arrays.hashCode methods added in release 1.5.
  • Combine the hashcode c into result as follows: result = 31 * result + c;

It would be correct to follow the recipe as is, even with just one field. Just do the appropriate action depending on the type of the field.

Note that there are libraries that actually simplify this for you, e.g. HashCodeBuilder from Apache Commons Lang, or just Arrays.hashCode/deepHashCode from java.util.Arrays.

These libraries allows you to simply write something like this:

@Override public int hashCode() {
    return Arrays.hashCode(new Object[] {
        field1, field2, field3, //...
    });
}

Apache Commons Lang example

Here's a more complete example of using the builders from Apache Commons Lang to facilitate a convenient and readable equals, hashCode, toString, and compareTo:

import org.apache.commons.lang.builder.*;

public class CustomType implements Comparable<CustomType> {
    // constructors, etc
    // let's say that the "significant" fields are field1, field2, field3
    @Override public String toString() {
        return new ToStringBuilder(this)
            .append("field1", field1)
            .append("field2", field2)
            .append("field3", field3)
                .toString();
    }
    @Override public boolean equals(Object o) {
        if (o == this) { return true; }
        if (!(o instanceof CustomType)) { return false; }
        CustomType other = (CustomType) o;
        return new EqualsBuilder()
            .append(this.field1, other.field1)
            .append(this.field2, other.field2)
            .append(this.field3, other.field3)
                .isEquals();
    }
    @Override public int hashCode() {
        return new HashCodeBuilder(17, 37)
            .append(field1)
            .append(field2)
            .append(field3)
                .toHashCode();
    }
    @Override public int compareTo(CustomType other) {
        return new CompareToBuilder()
            .append(this.field1, other.field1)
            .append(this.field2, other.field2)
            .append(this.field3, other.field3)
                .toComparison();
    }
}

These four methods can be notoriously tedious to write, and it can be difficult to ensure that all of the contracts are adhered to, but fortunately libraries can at least help make the job easier. Some IDEs (e.g. Eclipse) can also automatically generate some of these methods for you.

See also

polygenelubricants
@polygenelubricants I consider this as "the correct answer", so thank you.
InsertNickHere
+1 for this informative answer on hashcode and the Arrays.hashCode() suggestion; first time I've seen that and I like it!
Yanick Rochon
@poly Thanks again for this long and good understandable answer. But I have missed some other point - for now, I don't have to implement a hashCode (see Michaels comment), but maybe I have to in the future-so your answer is just to early in time. ;)
InsertNickHere
+1  A: 

If you want objects with different ids to identified by that id all you need to do is return it/compare it.

private final int id;

public int hashCode() { return id; }

public boolean equals(Object o) { 
    return o instanceof ThisClass && id == ((ThisClass)o).id;
}
Peter Lawrey
@Peter your equals function is not implemented in the correct manner, but just returning the id as hashValue I count as answer to my question, therefore +1.
InsertNickHere
What is wrong with the equals() ? If only id field is enough to override hashCode(), Peters equals() implementation seems perfectly fine.
krmby
@krmby Hm, afaik there has to be a null check so that it returns false in this case.
InsertNickHere
instanceof will do the nullcheck for you. This equals() is ugly, but seems to be correct.
unbeli
+1  A: 

It does not matter that how many fields are used to calculate hashCode. But it matters working with equals(). If A equals B, their hashCode must be same.

If you hate hashCode:) and your object never be put to hash based containers(HashMap, HashSet..), just leave hashCode() alone, let its base class to calculate hashCode.

卢声远 Shengyuan Lu
Good point, you don't need to implement equals/hashcode for most objects.
Peter Lawrey
@Michael I ask because I now use a HashMap to get the O(1) time for getting an entry.
InsertNickHere
@InsertNickHere: sorry for mis-reading your question. Be sure your object is put to HashMap as a KEY not a value.
卢声远 Shengyuan Lu
@Michael Oh, see, you pointed me to something i totally get wrong. Thought I have to write hash code evan if i use my class as values. D'oh, how stupid can I be? ;-)
InsertNickHere