NullPointerException of the get() method of HashMap

NullPointerException of the get() method of HashMap

@author:Jingdai
@date:2020.12.07

I found a bug in writing code today. The get() method of HashMap keeps reporting a null pointer exception. Now let’s record it.

Look at the code below.

private HashMap<Integer, Integer> cache;
private LinkedList<Integer> keyList;
private int capacity;

public LRUCache(int capacity) {
    
    
    cache = new HashMap<>();
    keyList = new LinkedList<>();
    this.capacity = capacity;
}

// Put it in the front if use
public int get(int key) {
    
    
    keyList.remove(new Integer(key));
    keyList.addFirst(key);
    return cache.get(key);
}

The last line cache.get(key)has been reported NullPointerException. First of all, LRUCachethe object I was newout, would be in the constructor cacheto initialize and will not be null, debug is also verified, cacheit is not null.

Then go to view the Java API, as follows:

V get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

The Java API clearly states that when the given key does not exist, it will return instead of nullthrowing NullPointerException.

The explanation is not the problem here. Since it will return null, it seems to understand. If the key value does not exist, when returning null, if the basic data type is used to receive the result, such as the following code.

public static void main(String[] args) {
    
    
    HashMap<Integer, Integer> map = new HashMap<>();
    int i = map.get(5);
}

This will be nullassigned i, there will be an automatic unpacking process, calls the return value of intValue()the method and assigns the result to i, but the return value is null, then null.intValue()there will be NullPointerException. The beginning return cache.get(key);is the same, the return value is null, but is a function of type int, also appeared at the time of conversion NullPointerException.

Therefore, although HashMapthe get()method does not appear NullPointerException, but still may appear at the time of packaging and basic type conversion NullPointerException, we need to pay attention to programming.

Guess you like

Origin blog.csdn.net/qq_41512783/article/details/110819487