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 strings, 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

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -