Create hash from string and int

前端 未结 6 1766
离开以前
离开以前 2021-02-07 20:14

I remember eclipse and idea have this template to automatically create an object\'s hashCode based on its attributes.

One of the strategies if a number and a string is u

6条回答
  •  失恋的感觉
    2021-02-07 20:57

    Eclipse always does roughly the same hashing function, here's an example for a class with an in and String as fields

        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + this.interger;
            result = prime * result + ((this.string == null) ? 0 : this.string.hashCode());
            return result;
        }
    

    They always pick 31 as the prime, and then multiple by build in hash functions or the value if its a primitive. Something like this wouldn't be hard to create as a method.

         public int hashCode(Object ... things) {
             final int prime = 31;
             int result = 1;
             for(Object thing : things) {
                 result = prime * result + thing.hashCode();
             }
             return result;
         }
    

提交回复
热议问题