Reputation: 241
Is there any difference between these two statements when I just want to set an 'if' statement?
// it is a HashMap
if (map.keySet().contains(myKey)) { //do something...}
if (map.containsKey(myKey)){ //do the same thing...}
Upvotes: 21
Views: 12990
Reputation: 2908
containsKey()
is faster. keySet()
returns a set backed by the HashMap itself, and its contains()
method calls containsKey()
.
This is its implementation:
public final boolean contains(Object o) { return containsKey(o); }
Upvotes: 17