【发布时间】:2013-12-27 22:29:12
【问题描述】:
我正在尝试通过添加一个新字符并反过来减去它来测试 String 哈希码的工作原理,但是当我进行计算时它没有给我正确的答案。
例如
int PRIME = 31;
//this will print 1687846330
System.out.println("mlkjihgfedcb".hashCode());
//this will print 783628775 which equals to "mlkjihgfedcba".hashCode();
System.out.println(("mlkjihgfedcb".hashCode() * PRIME + (int) 'a'));
//this will print 25278344 which doesn't equals to "mlkjihgfedcb".hashCode()
System.out.println(("mlkjihgfedcba".hashCode() - (int) 'a') / PRIME);
我想知道我在上面的最后一步中是否正确地进行了数学运算?溢出对于计算应该不重要吧?
【问题讨论】:
-
这在很多层面上都是错误的
-
@Bill 我没有看到人们解释为什么它在那个线程中不可逆......你在哪里看到它?
-
如果两个不同的字符串可以产生相同的结果,您无法知道其中的哪一个字符串产生了该哈希码,因此您无法反转计算。
标签: java int hashcode string-hashing