我运行了下面这段脚本(Java),结果却很奇怪。有人能帮忙解释一下吗?
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}));
}
}
}
日志结果(它们彼此不同):
//...
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
//...
---- 背景 ----
我想为 @Cacheable 注解(Spring & ehCache)使用自己的 keyGenerator。
public Object generate(Object target, Method method, Object... params) {
int key = Objects.hashCode(method.getName(), params);
log.info("key = " + key);
return key;
}
在这种情况下,我发现缓存总是无法命中。
那么我必须更改为这个:
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()
是基于标识的,而不是基于内容的。 - Louis Wasserman