java.util.Map.containsKey(Object key)
documentation says:
@throws ClassCastException if the key is of an inappropriate type for this map
.
The java.util.HashMap.containsKey(Object key)
implementation does not say anything about it.
My problem:
If I create a Map<String,String> map = new HashMap<>();
and call the containsKey
method with an Integer
the value is hashed (as a String
) but the method does not throw an Exception
.
Incidentally, the hash of 4 differs from the hash of "4".
Is this really the intended behavior?
containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
What happens if we put a key object in a HashMap which exists? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.
Generally O(1), but if we're using a bad hashCode function, we need to add multiple elements to one bucket so it can be O(n) in worst case.
get(Object) does explicitly warn about the subtle differences between Map. get(Object) and Map. containsKey(Object) : If this map permits null values, then 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 .
This seems to be an optional restriction, not applied in HashMap
.
As stated in API for containsKey
:
[...]
Throws:
ClassCastException
- if the key is of an inappropriate type for this map (optional)
Note the "optional", and see linked documentation:
Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit
null
elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typicallyNullPointerException
orClassCastException
. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the collection may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With