“非空”是指在这个问题中包含至少一个非零字符的字符串。
作为引用,这里是 hashCode
实现:
1493 public int hashCode() {
1494 int h = hash;
1495 if (h == 0) {
1496 int off = offset;
1497 char val[] = value;
1498 int len = count;
1499
1500 for (int i = 0; i < len; i++) {
1501 h = 31*h + val[off++];
1502 }
1503 hash = h;
1504 }
1505 return h;
1506 }
并且算法在文档中指定。
在整数溢出发生之前,答案很简单:不会。但我想知道的是,由于整数溢出,非空字符串的哈希码是否可能为零?你能 build 一个吗?
理想情况下,我正在寻找的是数学演示(或链接)或构造算法。
最佳答案
当然。例如,字符串 f5a5a608 的哈希码为零。
我通过简单的蛮力搜索发现:
public static void main(String[] args){
long i = 0;
loop: while(true){
String s = Long.toHexString(i);
if(s.hashCode() == 0){
System.out.println("Found: '"+s+"'");
break loop;
}
if(i % 1000000==0){
System.out.println("checked: "+i);
}
i++;
}
}
编辑: 从事 JVM 工作的 Joseph Darcy 甚至编写了一个可以 construct a string with a given hashcode 的程序(在 switch/case 语句中测试字符串的实现)基本上是反向运行哈希算法。
关于java - 非空字符串的哈希码可以为零吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18746394/