class Fib {
public Map<Integer, Integer> memo = new HashMap<Integer, Integer>();
Fib() {
memo.put(0, 1);
memo.put(1, 1);
}
public Integer fibonacciMemoized(Integer n) {
if (memo.containsKey(n)) {
return memo.get(n);
} else {
int fibo = fibonacciMemoized(n-1) + fibonacciMemoized(n-2);
return memo.put(n, fibo);
}
}
}
这段代码给出了一个NullPointerException
。但是,如果我将最后一个返回语句分解为:
memo.put(n, fibo);
return fibo;
然后就可以了。怎么会? put()
不返回放入 map 的值吗?
最佳答案
不,它没有。您可以阅读 JavaDocs ,那里清楚地指出 put
返回与键关联的 previous 值,如果没有键的映射,则返回 null
。
V put(K key, V value)
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
Parameters:
key - key with which the specified value is to be associated
value - value to be associated with the specified keyReturns: the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)
因此,对于您的代码,必须使用以下内容:
memo.put(n, fibo); // will NOT return the value
return fibo; // and here it is returned
关于java - 为什么这个 Memoized Fibonacci 的实现不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27834764/