tags:

views:

46

answers:

2

I have three fields namely

  1. Number1
  2. Number2
  3. 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. Any help would be appreciated.

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;
}

}

A: 

I take it's a special version of hashCode. Otherwise you would need to overwrite hashCode, don't define a new method. Containers like HashSet don't get your own hash code.

  • So for your specialized version for long, you do not need to use the xor (^) because it's already long. Just use the long value.
  • When using hashCode of String it's not for long, just for int, so it will not "use" all your space. You could duplicate the hashCode of String with longs for your purpose.
  • else looks good.

(By the way, members should be called with lower letters and Time should be private as well.)

Peter Kofler
+1  A: 

You can just use HashCodeBuilder from commons-lang and not have to worry about doing this by hand anymore.

@Override
public int hashCode() {
 // you pick a hard-coded, randomly chosen, non-zero, odd number
 // ideally different for each class
 return new HashCodeBuilder(17, 37).
   append(Number1).
   append(Number2).
   append(Time).
   toHashCode();
}

btw, it's convention in Java for variable names to start with a lowercase. You're going to find it confusing to name variables things like Number1, Number2, etc., as people will confuse these with the names of types (such as String, Number, Long, etc.).

matt b