Create hash from string and int

前端 未结 6 1961
离开以前
离开以前 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:50

    A hashcode method is something that potentially be called many times, and is therefore worth optimizing. If the calculation is complicated, consider memoizing the hash value. Also, avoid doing things that entail more calculation than is necessary. (For example, the StringBuilder solution spends most of its time creating the temporary String.)

    The other thing I want to point out is that the quality of the hash is important. You want to avoid any hashcode algorithm that maps lots of common keys. If that happens, hash table lookup may no longer be O(1). (In the worst case it will be O(N) ... i.e. equivalent to a linear search!). Here's an example of a bad hash function:

    int hashcode() {
        int hash = 1;
        for (int val : this.values) {
            hash = hash * value;
        }
        return hash;
    }
    

    Consider what happens if an element of this.values is zero ...

提交回复
热议问题