Can a non-empty string have a hashcode of zero?

后端 未结 2 1717
离开以前
离开以前 2020-12-15 16:53

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 :<

相关标签:
2条回答
  • 2020-12-15 17:42

    just be care of that int h;. It may overflow, every string that satisfy h % 2^31 == 0 may lead to this.

    public class HelloWorld {
        public static void main(String []args) {
           System.out.println("\u0001!qbygvW".hashCode());
            System.out.println("9 $Ql(0".hashCode());
            System.out.println(" #t(}lrl".hashCode());
            System.out.println(" !!#jbw}a".hashCode());
            System.out.println(" !!#jbw|||".hashCode());
            System.out.println(" !!!!Se|aaJ".hashCode());
            System.out.println(" !!!!\"xurlls".hashCode());
        }
    }
    

    A lot of strings...

    0 讨论(0)
  • 2020-12-15 17:48

    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.

    0 讨论(0)
提交回复
热议问题