我有以下代码:
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class DynamicFib
{
private static Map<Integer, BigInteger> myMap = new HashMap<>();
static {
myMap.put(0, BigInteger.ZERO); //fibonacci(0)
myMap.put(1, BigInteger.ONE); //fibonacci(1)
}
public static BigInteger fibonacci(int x)
{
// System.out.println("x = [" + x + "]");
return myMap.computeIfAbsent(x, n -> fibonacci(n - 2).add(fibonacci(n - 1)));
}
public static void main(String[] args)
{
System.out.println("l = " + fibonacci(25));
System.out.println("myMap = " + myMap);
System.out.println("myMap = " + myMap.keySet().size());
}
}
控制台输出:
l = 75025
myMap = {0=0, 1=1, 2=1, 3=2, 4=3, 5=5, 6=8, 7=13, 8=21, 9=34, 10=55, 11=89, 12=144, 13=233, 14=377, 15=610, 16=987, 17=1597, 18=2584, 19=4181, 20=6765, 21=10946, 22=17711, 23=28657, 24=46368}
myMap = 31
备忘录只有25个元素,但大小返回31。这是哈希映射实现中的错误吗?
我将哈希图更改为ConcurrentHashMap,如果我要求输入第9个或更多的斐波那契数,它将挂起。
但这可以正常工作,甚至可以返回1000个斐波那契数字!
答案 0 :(得分:3)
是的,HashMap.computeIfAbsent(K, Function)
Javadoc注意,您不应在计算过程中修改地图。如果您修改方法以首先检查地图是否包含x
作为键,然后像这样返回
public static BigInteger fibonacci(int x) {
if (!myMap.containsKey(x)) {
myMap.put(x, fibonacci(x - 2).add(fibonacci(x - 1)));
}
return myMap.get(x);
}
然后您会看到(正如我想的那样)
l = 75025
myMap = {0=0, 1=1, 2=1, 3=2, 4=3, 5=5, 6=8, 7=13, 8=21, 9=34, 10=55, 11=89, 12=144, 13=233, 14=377, 15=610, 16=987, 17=1597, 18=2584, 19=4181, 20=6765, 21=10946, 22=17711, 23=28657, 24=46368, 25=75025}
myMap = 26