java: Use of Raw type as method parameter errases all parametrized type information in parameter members

后端 未结 4 1114
孤街浪徒
孤街浪徒 2021-01-13 11:47

Please explain me why if I use the raw type A in the method test() , the get() method on my typed list returns an Object and not a B.:

public class test
{
           


        
4条回答
  •  旧时难觅i
    2021-01-13 12:20

    +1 for interesting test case.

    Looks like erasure erases everything, so in this case, you end up with.

    public List mGetBList()

    And erasure of List will result in public Object get( int ), which, of course, cannot be assigned to B.

    If there is no strong need for raw type in method signature, use generic form that you have provided, otherwise cast the object to B

    B lB = (B) pA.mGetBList().get(0);
    

提交回复
热议问题