Key existence check in HashMap

后端 未结 10 1961
走了就别回头了
走了就别回头了 2020-11-27 09:03

Is checking for key existence in HashMap always necessary?

I have a HashMap with say a 1000 entries and I am looking at improving the efficiency. If the HashMap is b

10条回答
  •  借酒劲吻你
    2020-11-27 09:50

    You won't gain anything by checking that the key exists. This is the code of HashMap:

    @Override
    public boolean containsKey(Object key) {
        Entry m = getEntry(key);
        return m != null;
    }
    
    @Override
    public V get(Object key) {
        Entry m = getEntry(key);
        if (m != null) {
            return m.value;
        }
        return null;
    }
    

    Just check if the return value for get() is different from null.

    This is the HashMap source code.


    Resources :

    • HashMap source code Bad one
    • HashMap source code Good one

提交回复
热议问题