为什么Objects.hash()对于同一输入返回不同的值? [英] Why Objects.hash() returns different values for the same input?
问题描述
我运行了以下脚本(java),它给了我奇怪的结果. 有人可以帮忙解释吗?
I ran the follow script(java), and it gave me the weird result. Does anyone can help to explain?
import java.util.Objects;
import org.apache.log4j.Logger;
public class CacheTester {
private static final Logger log = Logger.getLogger(CacheTester.class);
@Test
public void hashCodeTest() {
for (int i = 0; i < 50; i++) {
// if I remove the third parameter, it works fine
log.info(Objects.hash("getDemoCache", "1", new int[]{1, 2}));
}
}
}
日志结果(彼此不同):
Log Result(they are different from each other):
//...
2015-04-29 17:43:20 INFO CacheTester:42 - 1431904540
2015-04-29 17:43:20 INFO CacheTester:42 - 1859187447
2015-04-29 17:43:20 INFO CacheTester:42 - -2146933580
2015-04-29 17:43:20 INFO CacheTester:42 - -2074242201
2015-04-29 17:43:20 INFO CacheTester:42 - 1363170000
2015-04-29 17:43:20 INFO CacheTester:42 - 1040980265
2015-04-29 17:43:20 INFO CacheTester:42 - 1639331053
2015-04-29 17:43:20 INFO CacheTester:42 - 570765746
2015-04-29 17:43:20 INFO CacheTester:42 - -2023288896
2015-04-29 17:43:20 INFO CacheTester:42 - -1892732019
2015-04-29 17:43:20 INFO CacheTester:42 - 1464306601
2015-04-29 17:43:20 INFO CacheTester:42 - 921799986
2015-04-29 17:43:20 INFO CacheTester:42 - 1037804977
//...
----背景----
---- Background ----
我想将自己的keyGenrator用于@Cacheable注释(Spring& ehCache).
I wanted to used my own keyGenrator for @Cacheable annotation(Spring & ehCache).
public Object generate(Object target, Method method, Object... params) {
int key = Objects.hashCode(method.getName(), params);
log.info("key = " + key);
return key;
}
在这种情况下,我发现缓存总是丢失的.
In this case, I find the cache are always missed.
然后我必须更改为:
public Object generate(Object target, Method method, Object... params) {
int result = method.getName().hashCode() : 0;
result = 31 * result + Objects.hashCode(params);
return result;
}
谢谢
推荐答案
这是因为int[]
的hashCode
没有被覆盖.即使条目相同,也没有理由为什么int[]
的两个实例应该具有相同的hashCode
.
It's because hashCode
for int[]
is not overridden. There is no reason why two instances of int[]
should have the same hashCode
, even if the entries are the same.
尝试一下:
System.out.println(new int[] {1, 2}.hashCode());
System.out.println(new int[] {1, 2}.hashCode());
几乎可以肯定会看到两个不同的整数.
You will almost certainly see two different integers.
对数组使用Objects.hash
的一种好方法是传递Arrays.hashCode(array)
而不是实际数组.您可以这样做:
A good way to use Objects.hash
with arrays is to pass Arrays.hashCode(array)
instead of the actual array. In your case you could do:
Objects.hash("getDemoCache", "1", Arrays.hashCode(new int[]{1, 2}))
这篇关于为什么Objects.hash()对于同一输入返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!