gpt4 book ai didi

java - java中只使用key对象的引用的缓存(而不是hashCode或equals)

转载 作者:太空宇宙 更新时间:2023-11-04 09:10:05 24 4
gpt4 key购买 nike

我有一个类可以多次运行一些昂贵的计算。我想为其添加一个缓存,例如:

private Map<MyObj, Result> cache = new HashMap<>();

private Result getFoo(MyObj myObj) {
Result r = cache.get(myObj);
if (r == null) {
r = expensiveCalculation(myObj);
}
return r;
}

因为我知道两个 MyObj-s 相等的唯一方法是它们相同(引用),所以我不希望缓存计算 hashCode() 和 equals()。有没有办法让 Map 仅使用引用进行散列?

或者像这样更好的缓存方式?

最佳答案

请注意,这没有优化。没有任何好处,而且您的代码会变得更加复杂。

Since I know the only way two MyObj-s can be equal is if they're identical (the reference), I don't want the cache to calculate the hashCode() and equals().

始终计算hashCode以在哈希表中进行存储。在关键对象上调用 equals 方法之前,哈希表实现中的常见优化是首先检查相同的引用。

关于java - java中只使用key对象的引用的缓存(而不是hashCode或equals),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59754616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com