java - 为什么这个 Memoized Fibonacci 的实现不起作用?

标签 java dictionary hashmap fibonacci

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 key

Returns: 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/

相关文章:

java - 如何从 Maven 中的父项目中排除依赖项?

java - 如何让我的 Android 应用程序可以从锁屏访问?

java - "Resource bundle"用于保存其他本地化数据

java - 如何初始化静态 map ?

java - 通过返回 ArrayList 并为其赋值,将 Element 添加到 HashMap 中的 ArrayList

java - 将包名转换为路径

java - 为什么我们在构造函数中调用 super()

java - 在java中迭代和修改集合时创建临时缓冲区的优点

java - 我们如何比较java中的两个 HashMap

java - 如何检查每个员工的电子邮件是否与搜索值匹配