非空字符串的哈希码是否可以为零? [英] Can a non-empty string have a hashcode of zero?

查看:654
本文介绍了非空字符串的哈希码是否可以为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过非空,我的意思是在这个问题中至少包含一个非零字符的字符串。



作为参考,这里是实现:

pre $ 1493 public int hashCode(){
1494 int h =散列;
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}

并且在文档中指定了该算法。



在发生整数溢出之前,答案很简单:没有。但是我想知道的是,如果由于整数溢出,非空字符串可能具有零散列码?你可以构建一个吗?



我想要的是理论上的数学演示(或指向一个的链接)或构造算法。 $ b

解决方案

当然。例如,字符串 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循环;
}
if(i%1000000 == 0){
System.out.println(checked:+ i);
}
i ++;




编辑:约瑟夫达西,他曾在JVM上工作过,甚至写过一个程序,可以用给定的哈希代码构建一个字符串(以测试在switch / case语句中实现字符串)通过反向运行哈希算法。


By "non-empty", I mean in this question a string which contains at least one non-zero character.

For reference, here's the hashCode implementation :

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    }

and the algorithm is specified in the documentation.

Before an integer overflow occurs, the answer is easy: it's no. But what I'd like to know is if, due to integer overflow, it's possible for a non-empty string to have a hashcode of zero? Can you construct one?

What I'm looking for would ideally be a mathematical demonstration (or a link to one) or a construction algorithm.

解决方案

Sure. The string f5a5a608 for example has a hashcode of zero.

I found that through a simple brute force search:

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++;
    }       
}

Edit: Joseph Darcy, who worked on the JVM, even wrote a program that can construct a string with a given hashcode (to test the implementation of Strings in switch/case statements) by basically running the hash algorithm in reverse.

这篇关于非空字符串的哈希码是否可以为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆