I have come across a strange behavior of Java that seems like a bug. Is it? Casting an Object to a generic type (say, K) does not throw a ClassCastExcepti
As cletus says, erasure means that you can't check for this at runtime (and thanks to your casting you can't check this at compile time).
Bear in mind that generics are a compile-time only feature. A collection object does not have any generic parameters, only the references you create to that object. This is why you get a lot of warning about "unchecked cast" if you ever need to downcast a collection from a raw type or even Object - because there's no way for the compiler to verify that the object is of the correct generic type (as the object itself has no generic type).
Also, bear in mind what casting means - it's a way of telling the compiler "I know that you can't necessarily check that the types match, but trust me, I know they do". When you override type checking (incorrectly) and then end up with a type mismatch, who ya gonna blame? ;-)
It seems like your problem lies around the lack of heterogenous generic data structures. I would suggest that the type signature of your method should be more like private static, but I'm not convinced that gets you anything really. A list of pairs basically is a map, so contructing the typesafe vals parameter in order to call the method would be as much work as just populating the map directly.
If you really, really want to keep your class roughly as it is but add runtime type-safety, perhaps the following will give you some ideas:
private static void addToMap(Map map, Object ... vals, Class keyClass, Class valueClass) {
for(int i = 0; i < vals.length; i += 2) {
if (!keyClass.isAssignableFrom(vals[i])) {
throw new ClassCastException("wrong key type: " + vals[i].getClass());
}
if (!valueClass.isAssignableFrom(vals[i+1])) {
throw new ClassCastException("wrong value type: " + vals[i+1].getClass());
}
map.put((K)vals[i], (V)vals[i+1]); //Never throws ClassCastException!
}
}