0

I wonder if HashMap.put(key,null) has better performance over HashMap.remove(key) or not ?

code đờ
  • 554
  • 1
  • 9
  • 19
  • 1
    Possible repeat? https://stackoverflow.com/questions/15091148/hashmaps-and-null-values – Sourish Mukherjee Oct 13 '19 at 06:16
  • 1
    Welcome to stackoverflow.com. Please [take the tour](http://stackoverflow.com/tour) and read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask). Finally please read this [question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/) – Curiosa Globunznik Oct 13 '19 at 06:16
  • "which is better?" do yo mean which is **faster**? – Curiosa Globunznik Oct 13 '19 at 06:20
  • 1
    The two approaches are not equivalent. The call to `remove(key)` will actually remove the mapping whereas the call to `put(key, null)` will simply map the key to `null`. In other words, even after calling the latter, a call to `containsKey(key)` will return `true`. If your goal is to remove an entry from the map then use `remove`. And note that `Map` implementations are not required to allow `null` values and could instead throw a `NullPointerException`. – Slaw Oct 13 '19 at 06:27

3 Answers3

1

It depends on which approach you use in your code. HashMap.put(key,null) is different from HashMap.remove(key) as put is used for adding some value and remove is used for removing. The time complexity of HasMap is O(1). As both are used in HashMap so their time Complexity will be same.So i think they both are faster.

0

Which one is better totally depends on how you use your HashMap in your code since they are two different methods doing two different things.

If you are only considering performance and if you are merely curious about which one is faster, there would be no big difference since HashMap has time complexity of O(1) for both put and remove.

I am guessing there might be a small performance benefit for remove since it reduces the total number of keys in HashMap and it is definitely possible for HashMap to have time complexity of O(n) in the worst case, but I think it is negligible.

wWw
  • 147
  • 9
0

On top of @Slaw's comment, if you use HashMap.put(key,null) in lieu of HashMap.remove(key), the size of the map would not change. This could cause unintended side effects.

    Map<String, String> test = new HashMap<>();
    System.out.println("Size: " + test.size());  // Size: 0

    test.put("John", null);
    System.out.println("Size: " + test.size());  // Size: 1