Does java.util.HashMap.containsKey(Object key) implementation violate java.util.Map.containsKey(Object key) documentation?

eventhorizon :

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.

Btw: The hash of 4 differs from the hash of "4".

Is this really the intended behavior?

THX in advance!

Mena :

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, typically NullPointerException or ClassCastException. 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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=440472&siteId=1