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
Java's generics are done using "type erasure", meaning that at runtime, the code doesn't know you have a Map
If you care about the types at compile time, don't call them Object. :) Make your addToMap function look like
private static void addToMap(Map map, K key, V value) {
If you want to insert multiple items in the map, you'll want to make a class kinda like java.util's Map.Entry, and wrap your key/value pairs in instances of that class.