Key existence check in HashMap

后端 未结 10 1987
走了就别回头了
走了就别回头了 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:49

    Do you mean that you've got code like

    if(map.containsKey(key)) doSomethingWith(map.get(key))

    all over the place ? Then you should simply check whether map.get(key) returned null and that's it. By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.

提交回复
热议问题