5 ms·
that's because in java you can't distinguish between no object found, and null with the default hashmap implementation. in this "benchmark" it would probably no
by rjzzleep 13y ago
that's because in java you can't distinguish between no object found, and null with the default hashmap implementation. in this "benchmark" it would probably not matter though.
> A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.
http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html#get(java.lang.Object) http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.h...
- loeg 13y agoAssuming you care about the distinction between null and no such key (for many applications you can avoid storing null, IMO), you can actually perform the containsKey() after the get() for only keys which get() returns null. I think that see all of the perf overhead of a single lookup if most values are non-null.
- silvestrov 13y agoIn java 1.8 there is a Map.getOrDefault(key, defaultValue) method which can be used to distinguish between null and not-found.