I recently stumbled across the Javadoc for the Collection.checkedMap
family of functions for creating dynamically typesafe views of the standard Collections types. Considering that they add another layer of safety on top of the collections that diagnoses a relatively common programmer error, I would have figured that they would be more popular. For some reason, though, in all of the large Java projects I've worked on, I've not seen them used once.
My question is this: is there a particular reason that Java programmers don't use these checked wrappers more frequently? Or is it just lack of benefit/lack of knowledge of their existence?
EDIT: To clarify my question, the generic versions of the collections still contain type-unsafe functions. Map
's containsKey
, containsValue
, remove
, and get
all operate on Object
, for example. My main question is, given this type-unsafety, why more people don't use the checked implementations to diagnose runtime type violations.
These classes are only really necessary if one is abusing (or not using) generics. It duplicates at runtime checks that should be sufficient to perform at compile time through the type safety guarantees by the generics engine.
As a result, using these methods is only really interesting in the context of API designers who don't trust the users of the library, and want to protect either themselves, or the users, from the users using the map improperly.
Here's the short of it: if your code compiles without raw type warnings or any unchecked conversion/type warnings, you are guaranteed that the checked*
methods don't give you any benefit; they are only a runtime hit.
Edit
You seem to be concluding that since remove
, get
, etc operate on an Object
, they are somehow type-unsafe. They are not. None of those methods will store its operand in the map, so you are certainly not compromising the type safety of the map itself. Those methods take an Object for one main reason: for backwards compatibility. There was never any strict requirement that look-ups needed to adhere to the same class. For example, if an instance of class A and an instance of class B could somehow be equal to each other, putting a
into the map and then calling remove(b)
should remove a
's mapping.
This behaviour needed to be supported once generics were added to preserve backwards compatibility. Thus they couldn't update the interface to something like remove(K)
as existing code may rely on being able to remove a mapping given an instance of a completely different class. It is however not type unsafe, and using the checked version of the map doesn't change this behaviour in the slightest.
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