java - Hashcode generated by Eclipse -
in have read several answers related implementation of hashcode , suggestion use xor operator. (e.g. why xor used in java hashcode() bitwise operators used rarely?).
when use eclipse generate hashcode function field
object , timestamp
long, output is:
public int hashcode() { final int prime = 31; int result = 1; result = prime * result + field == null) ? 0 : field.hashcode()); return result; }
is there reason not using xor operator below?
result = prime * result + (int) (timestamp ^ (timestamp >>> 32));
eclipse takes safe way out. although calculation method uses prime, multiplication, , addition slower single xor, gives overall better hash code in situations when have multiple fields.
consider simple example - class 2 string
s, a
, b
. can use
a.hashcode() ^ b.hashcode()
or
a.hashcode() * 31 + b.hashcode()
now consider 2 objects:
a = "abc"; b = "xyz"
and
a = "xyz"; b = "abc"
the first method produce identical hash codes them, because xor symmetric; second method produce different hash codes, good, because objects not equal. in general, want non-equal objects have different hash codes possible, improve performance of hash-based containers of these objects. 31*a+b
method achieves goal better xor.
note when dealing portions of same object, in
timestamp ^ (timestamp >>> 32)
the above argument weaker: encountering 2 timestamps such difference between them upper , lower parts swapped harder imagine 2 objects swapped a
, b
field values.
Comments
Post a Comment