Casting to generic type in Java doesn't raise ClassCastException?

后端 未结 5 1379
别跟我提以往
别跟我提以往 2020-11-28 15:46

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 16:17

    Java's generics are done using "type erasure", meaning that at runtime, the code doesn't know you have a Map -- it just sees a Map. And since you're converting the stuff to Objects (by way of your addToMap function's param list), at compile time, the code "looks right". It doesn't try to run the stuff when compiling it.

    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.

提交回复
热议问题