I'm trying to get the 1st to 20th term in the Fibonacci sequence using the function computeIfAbsent()
in class HashMap
. Here is the code:
@Test
public void getFibMap() {
Map<Integer, Long> map = new HashMap<>();
map.put(1, 1L);
map.put(2, 1L);
fib(20, map);
map.forEach((x, y) -> System.out.printf("key : %d --> value : %d\n", x,
y.));
}
public Long fib(Integer n, Map<Integer, Long> map) {
return map.computeIfAbsent(n, v -> fib(n - 1, map) + fib(n - 2, map));
}
But when the program ends, two numbers, 19 and 20, are missing, which are supposed to be calculated. Here is the console:
key : 1 --> value : 1
key : 2 --> value : 1
key : 3 --> value : 2
key : 4 --> value : 3
key : 5 --> value : 5
key : 6 --> value : 8
key : 7 --> value : 13
key : 8 --> value : 21
key : 9 --> value : 34
key : 10 --> value : 55
key : 11 --> value : 89
key : 12 --> value : 144
key : 13 --> value : 233
key : 14 --> value : 377
key : 15 --> value : 610
key : 16 --> value : 987
key : 17 --> value : 1597
key : 18 --> value : 2584 //finished here
Process finished with exit code 0
When I specify an explicit size for the map to its constructor, these two numbers are calculated. I don't know why:
@Test
public void getFibMap() {
Map<Integer, Long> map = new HashMap<>(25);
map.put(1, 1L);
map.put(2, 1L);
fib(20, map);
map.forEach((x, y) -> System.out.printf("key : %d --> value : %d\n", x,
y));
}
public Long fib(Integer n, Map<Integer, Long> map) {
return map.computeIfAbsent(n, v -> fib(n - 1, map) + fib(n - 2, map));
}
Console:
...
key : 12 --> value : 144
key : 13 --> value : 233
key : 14 --> value : 377
key : 15 --> value : 610
key : 16 --> value : 987
key : 17 --> value : 1597
key : 18 --> value : 2584
key : 19 --> value : 4181
key : 20 --> value : 6765 //finished here
Process finished with exit code 0
Please, can somebody tell me why this happens?