Hash Code for a group of three fields

后端 未结 2 1151
别那么骄傲
别那么骄傲 2021-01-28 11:00

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 (

2条回答
  •  执念已碎
    2021-01-28 11:24

    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.).

提交回复
热议问题