下面的精简程序对我来说效果很好,但是当我将 hashVal 声明(粗体)移到 for 循环之外时,我的程序无法正确运行。在插入哈希映射时,为什么我需要它在 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) !**
}
}
}