说到hash,顺带一提:java中String.hashCode()方法的算法如下:str.charAt(0) * 31n-1 + str.charAt(1) * 31n-2 + ... + str.charAt(n-1)
这个算法肯定是有可能碰撞的,由于测试中,可能需要两个String hash之后的值 会碰撞,所以特地搜索了一下,其中“Aa”和“BB”两个的hashCode取值是相同的,都是2112
其中的中文也是有的 参考这边文档
制作相同hashcode的代码块System.out.println("\"柳志崇\".hashCode()="+"柳志崇".hashCode());System.out.println("\"柳山왡\".hashCode()="+"柳山왡".hashCode());int aa= '柳'3131+'志'*31+'崇' ;System.out.println("aa=" + aa);int ccint = (aa- ('柳'3131+ '山'*31) );System.out.println("ccint=" + ccint);char cc = (char)ccint;System.out.println("cc=" + cc);
上面的算法基本是很明显,实现如何拼凑出两个有相同hash的String