Can Java's hashCode produce same value for different strings?

前端 未结 12 873
情歌与酒
情歌与酒 2020-11-28 08:58

Is it possible to have same hashcode for different strings using java\'s hashcode function?or if it is possible then what is the % of its possibility?

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 09:50

    This wouldn't directly answer your question, but I hope it helps.

    The below is from the source code of java.lang.String.

    /**
     * Returns a hash code for this string. The hash code for a
     * String object is computed as
     * 
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * 
    * using int arithmetic, where s[i] is the * ith character of the string, n is the length of * the string, and ^ indicates exponentiation. * (The hash value of the empty string is zero.) * * @return a hash code value for this object. */ public int hashCode() { int h = hash; int len = count; if (h == 0 && len > 0) { int off = offset; char val[] = value; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; }

提交回复
热议问题