下面的精简程序对我来说效果很好,但是当我将 hashVal 声明(粗体)移到 for 循环之外时,我的程序无法正确运行。在插入 HashMap 时我需要将它放在 for 循环内有什么原因吗?在我的快速而草率的实现开始工作后,我在思考潜在的优化时发现了这一点。然而现在看来,快速而草率的实现是有效的,但不是我认为应该是优化的版本。
public class X
{
public static void foo()
{
Integer x1 = 0;
HashMap<Integer, BigInteger[]> map = new HashMap<Integer, BigInteger[]>();
int hashKey;
/* **BigInteger[] hashVal = new BigInteger[2];** <-----Does not run correctly
if I keep the hashVal declaration here. (1) */
for(x1 = 0; x1 <= 1048576; x1++)
{
BigInteger bx1 = BigInteger.valueOf(x1.intValue());
**BigInteger[] hashVal = new BigInteger[2];** (2)
BigInteger res;
/* Do lots and lots of big integer calculations and get a final result in res */
hashKey = res.hashCode();
/* Store res and x1 in hashmap */
hashVal[0] = res;
hashVal[1] = BigInteger.valueOf(x1.intValue());
map.put(hashKey, hashVal);
}
Integer x0;
for(x0 = 0; x0 <= 1048576; x0++)
{
/* do lots of BigInteger calculations to generate res */
hashKey = res.hashCode();
**bigNum = map.get(hashKey); <--------------Never returns a match if (1) above is enabled instead of (2) !**
}
}
}
最佳答案
...因为当 hashVal 位于循环外部时,它只会创建一次,因此在循环内部您不断地将相同的 BigInteger[] 插入映射中。换句话说,映射中的每个项目最终都是对同一个 BigInteger[] 的引用。这意味着您在上次循环期间放入 BigInteger[] 中的任何值都将是 map 中每个引用所看到的值。
当您在循环内创建一个新的 BigInteger[] 时,每次循环时 hashVal 都是对不同 BigInteger[] 的引用。
关于java - 使用 HashMap 时出现无法解释的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637984/