Key existence check in HashMap

后端 未结 10 1854
走了就别回头了
走了就别回头了 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<K, V> m = getEntry(key);
        return m != null;
    }
    
    @Override
    public V get(Object key) {
        Entry<K, V> 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
    0 讨论(0)
  • 2020-11-27 09:51
    1. If key class is your's make sure the hashCode() and equals() methods implemented.
    2. Basically the access to HashMap should be O(1) but with wrong hashCode method implementation it's become O(n), because value with same hash key will stored as Linked list.
    0 讨论(0)
  • 2020-11-27 09:58

    You can also use the computeIfAbsent() method in the HashMap class.

    In the following example, map stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100 and 200 to checking_account you can write:

    HashMap<String, ArrayList<Integer>> map = new HashMap<>();
    map.computeIfAbsent("checking_account", key -> new ArrayList<>())
       .add(100)
       .add(200);
    

    This way you don't have to check to see if the key checking_account exists or not.

    • If it does not exist, one will be created and returned by the lambda expression.
    • If it exists, then the value for the key will be returned by computeIfAbsent().

    Really elegant!

    0 讨论(0)
  • 2020-11-27 10:05

    Better way is to use containsKey method of HashMap. Tomorrow somebody will add null to the Map. You should differentiate between key presence and key has null value.

    0 讨论(0)
提交回复
热议问题