Java 它可以为不同的字符串生成相同的哈希代码。 我想起了我的教授教的一条规则,它在这里可能有用-
两个相同的字符串/值必须具有相同的哈希代码,但反之不成立 python中的示例Java 它可以为不同的字符串生成相同的哈希代码。 我想起了我的教授教的一条规则,它在这里可能有用-,java,hashcode,Java,Hashcode,两个相同的字符串/值必须具有相同的哈希代码,但反之不成立 python中的示例 >>散列('same-string') -5833666992484370527 >>>散列('same-string') -5833666992484370527 可能还有另一个字符串可以匹配相同的哈希代码,因此我们无法使用哈希代码派生密钥 两个不同字符串具有相同哈希代码的原因是冲突。 java哈希函数在这里返回相等的值。这是不正确的。每个字符都乘以不同的数字,所以字谜不一定返回相同的值。对不起,我的错!用一个
>>散列('same-string')
-5833666992484370527
>>>散列('same-string')
-5833666992484370527
可能还有另一个字符串可以匹配相同的哈希代码,因此我们无法使用哈希代码派生密钥
两个不同字符串具有相同哈希代码的原因是冲突。
java哈希函数在这里返回相等的值。这是不正确的。每个字符都乘以不同的数字,所以字谜不一定返回相同的值。对不起,我的错!用一个常见的例子更正了。为什么要为它们编写相同的哈希代码?它们是两个不同的字符串…:SSo,我可以说它可以生成2^32个不同的哈希,然后它会重复哈希代码吗?如果您设法识别出2^32个字符串,它们都有不同的哈希代码,那么是的,不在该列表中的任何其他字符串都将有与该列表中的相同的哈希代码。另一方面,这就是所谓的鸽子洞原理,在碰撞之前,你可能会经历少于2^32个字符串(大约2^16个字符串)。原因与生日悖论有关:“它散列的可能字符串的数量是无限的。”Java中的字符串具有最大大小,因为它们使用
char
数组和。因此,可能的字符串的数量不是无限的。那么,我可以说,对于2^32个不同的字符串,hashcode函数总是会产生不同的hashcode吗?@Zara实际上它甚至说的正好相反!如果有2^32个不同的字符串,则很可能会发生冲突(甚至是多个冲突)。@jory-是的,你是对的。这是生日悖论的一个例子。(并非完全不可能,2^32个不同的随机生成的字符串都会有不同的哈希代码。这几乎是不可能的。)他们在那里测试的字符串的字符集是什么?你能解释为什么吗?因为这是equals()和hashCode()方法之间的约定之一。如果根据equals()方法,两个对象不相等,则不能保证它们的哈希代码相同。请查看java文档,当映射到同一个bucket的哈希代码中的冲突数量较高时,这些攻击造成严重损害的风险可以得到缓解。
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> 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;
}
String str1 = "FB";
String str2 = "Ea";
System.out.println(str1.equals(str2));// false
System.out.println(str1.hashCode() == str2.hashCode()); // true
import java.util.HashMap;
public class TestHashCollision {
public static void main(String[] args) {
final String TEXT = "was stored earlier had the same hash as";
HashMap<Integer,String> hs=new HashMap<>();
long t1=System.currentTimeMillis();
long t2=System.currentTimeMillis();
for(long l=0;l<Long.MAX_VALUE;l++) {
String key="d"+l;
if(hs.containsKey(key.hashCode())) {
System.out.println("'"+hs.get(key.hashCode())+"' "+TEXT+" '"+key+"'");//System.exit(0);
} else {
hs.put(key.hashCode(),key);
}
t2=System.currentTimeMillis();
if(t2-t1>10000) {
t1=System.currentTimeMillis();
System.out.println("10 seconds gone! size is:"+hs.size());
}
}
System.out.println("Done");
}
}
"tensada".hashCode()
"friabili".hashCode());