Hash code for a group of three fields

I have three fields, namely

  • Number1
  • Number2
  • Time

I am trying to write a function in java that returns a unique hash value ( long must be a hash return value type ) for the above fields. This hash will then be used to store the database rows corresponding to the above fields in the HashSet. I am new to writing a hash function, can someone please see 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; } } 
0
source share
2 answers

I am using a special version of hashCode. Otherwise, you will need to overwrite hashCode , not define a new method. HashSet type containers do not receive their own hash code.

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

(By the way, members should be called with lower letters, and Time should also be closed).

+2
source

You can simply use the HashCodeBuilder from commons-lang and you no longer have to worry about it manually.

 @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, this is a convention in Java for variable names to start with a lowercase letter. You will encounter confusing variable names such as Number1 , Number2 , etc., since people will confuse them with type names (e.g. String , Number , Long , etc.) ..).

+2
source

Source: https://habr.com/ru/post/913717/


All Articles