I'm trying to implement the method fibCalc2 for calculation of nth Fibonacci number, but I'm getting the null pointer exception and I don't know how to go further. Is my solution make sense? Any help will be appreciated.
Note: HashTableMap is also implemented by myself, so it is different from the Java's implementation.
Update: NullPointerException on the last line of the code
Here is the code:
private static int callCount2;
private static Map<Integer, Long> ansMap = new LLQHashTableMap(10);
public static long fibCalc2(int n) {
if(n == 0 ||n == 1) return n;
if(ansMap.getSize() <= 2){
ansMap.define(0, (long) 0);
ansMap.define(1, (long) 1);
}
long tempVal1, tempVal2;
try {
long temp = ansMap.remove(n);
ansMap.define(n, temp);
} catch (Exception ex){
try {
long temp = ansMap.remove(n-1);
ansMap.define(n, temp);
tempVal1 = ansMap.getValue(n-1);
} catch (Exception ex1){
tempVal1 = fibCalc2(n-1);
}
try {
long temp = ansMap.remove(n-2);
ansMap.define(n, temp);
tempVal2 = ansMap.getValue(n-2);
} catch (Exception ex1){
tempVal2 = fibCalc2(n-2);
}
ansMap.define(n, tempVal1+tempVal2);
}
callCount2++;
return ansMap.getValue(n);
}
interface of my Map:
package adt;
import impl.KeyValuePair;
/**
* A generic map
* @param <K>
* @param <V>
*/
public interface Map<K, V> {
/**
* Adds a new key-value mapping to the map, which will
* replace a previous key-value mapping that has the
* same key, if it exists
*
* @param key of the key-value pair to be added
* @param value of the key-value pair to be added
*/
public void define(K key, V value);
/**
* Returns the value associated with the given key
* in the map, if one exists, or null if the key is
* not in the map
*
* @param key whose value we want to return
* @return value associated with the given key
*/
public V getValue(K key);
/**
* Removes the key-value pair from the map that has
* the given key value, and returns the associated value
* if it exists; if the key is not in the map, the map
* remains unchanged, and null is returned
*
* @param key of the key-value pair that we want to remove
* @return value associated with the given key before removal
*/
public V remove(K key);
/**
* Removes and returns some key-value pair from the map,
* if the map is not empty; if the map is empty, an
* exception is thrown
*
* @return some key-value pair from the map
* @throws Exception if the map is empty
*/
public KeyValuePair<K, V> removeAny() throws Exception;
/**
* @return the number of key-value pairs in the map
*/
public int getSize();
/**
* Removes all key-value pairs from the map
*/
public void clear();
/**
* @return a String representation of the map
*/
@Override
public String toString();
}