Java Generics with Class

后端 未结 6 2179
Happy的楠姐
Happy的楠姐 2020-12-31 16:03

So I have a map:

Map format = new HashMap();

And I would add elements to it like this:



        
6条回答
  •  春和景丽
    2020-12-31 16:29

    The reason you get this error is that in the first case the compiler sees that you pass it a Class object and is able to bind T to Integer at compile time, but in the second case the compiler only sees that you are passing it a Class object.

    At the end of the day, you will not be able to do

    Integer i = verifyType("100",format.get("Vendor Number"));
    

    in a type-safe way, since the compiler can't know that you will get an Integer (what if someone does a format.put("Vendor Number", X.class) just before that call?)

提交回复
热议问题