Java Generics with Class

后端 未结 6 2160
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:49

    It is strange for me, that your compiler on line

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

    complains about unchecked invocation but doesn't show an error like "Type mismatch: cannot convert from Object to Integer".

    This line just doesn't make sense to me. What do you expect verifyType to return if it receives Date.class as a second parameter? Also an Integer (then the return type of verifyType is invalid)? Or a Date? If you expect a Date, how is compiler expected to know that

    format.get("Vendor Number");
    

    returns Integer.class, but

    format.get("Vendor Dispatch");
    

    returns Date.class

    Invocation of

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

    must fail, as Date is not an Integer. So, in my opinion (and in opinion of my compiler) compilation of

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

    must fail.

提交回复
热议问题