Reputation: 615
I wonder if HashMap.put(key,null)
has better performance over HashMap.remove(key)
or not ?
Upvotes: 0
Views: 1529
Reputation: 1
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
Upvotes: 0
Reputation: 115
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.
Upvotes: 1
Reputation: 192
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.
Upvotes: 0