I have three fields, namely
- Number1
- Number2
- Time
I am trying to write a function in java that returns a unique hash value (long needs to be the return type of hash) for the above fields. This hash would then be used to store database rows corresponding to the above mentioned fields in a HashSet. I am new to writing a hash code function, can someone please review what I have.
public class HashCode {
private long Number1;
private long Number2;
String Time;
public HashCode(long Number1, long Number2, String Time){
this.Number1 = Number1;
this.Number2 = Number2;
this.Time = Time;
}
public long getHashCode() {
long hash = 3;
hash = 47 * hash + (long) (this.Number1 ^ (this.Number1 >>> 32));
hash = 47 * hash + (long) (this.Number2 ^ (this.Number2 >>> 32));
hash = 47 * hash + (this.Time != null ? this.Time.hashCode() : 0);
return hash;
}
}
I take it’s a special version of hashCode. Otherwise you would need to overwrite
hashCode, don’t define a new method. Containers likeHashSetdon’t get your own hash code.long, you do not need to use the xor (^) because it’s already long. Just use thelongvalue.hashCodeof String withlongs for your purpose.(By the way, members should be called with lower letters and
Timeshould be private as well.)