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?
If I understand correctly, 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..
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
hashCodewhen you overrideequals:Effective Java 2nd Edition hash code recipe
intvariable calledresult.inthashcodecfor each field:boolean, compute(f ? 1 : 0)byte, char, short, int, compute(int) flong, compute(int) (f ^ (f >>> 32))float, computeFloat.floatToIntBits(f)double, computeDouble.doubleToLongBits(f), then hash the resultinglongas in above.equalsmethod compares the field by recursively invokingequals, recursively invokehashCodeon the field. If the value of the field isnull, return 0.Arrays.hashCodemethods added in release 1.5.cintoresultas 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.
HashCodeBuilderfrom Apache Commons Lang, or justArrays.hashCode/deepHashCodefromjava.util.Arrays.These libraries allows you to simply write something like this:
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, andcompareTo: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
EqualsBuilderHashCodeBuilderToStringBuilderCompareToBuilderequalshashCodewhen you overrideequalstoStringComparable