I was recently bitten by a bug in which I had a Map with key type Long
, but I attempted to use it with keys of type String
. I essentially had something like:
Map<Long, Object> map;
...
String wrongType;
if (map.containsKey(wrongType)) {
// Do something
} else {
// Do something different
}
Because all of the keys in the map were of type Long, the code always executed the else
block.
Since the containsKey
and get
methods take an argument of type Object
, an object of any old type is accepted without complaint.
My confusion stemmed from the fact that the same entity is represented in two different ways in our system (sometimes as a Long
, sometimes as a String
); I can't easily change this. Is there any way I can catch an error like this while developing rather than during testing? Perhaps a compiler flag or some Eclipse option that is a little smarter about what sort of object I should be using with the containsKey
and get
methods (and their analogs in Set
, too...)