Creating a hash from several Java string objects

后端 未结 5 1316
情深已故
情深已故 2021-01-17 14:35

What would be the fastest and more robust (in terms of uniqueness) way for implementing a method like

public abstract String hash(String[] values);
         


        
5条回答
  •  醉酒成梦
    2021-01-17 14:56

    First, hash code is typically numeric, e.g. int. Moreover your version of hash function create int and then makes its string representation that IMHO does not have any sense.

    I'd improve your hash method as following:

    public int hash(String[] values) {
        long result = 0;
       for (String v:values) {
            result = result * 31 + v.hashCode();
        }
        return result;
    }
    

    Take a look on hashCode() implemented in class java.lang.String

提交回复
热议问题