Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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
{
    public class B{}
    public class C{}

    public class A<T extends C>
    {
        private List<B> aBList;

        public List<B> mGetBList()
        {
            return aBList;
        }
    }

    public test(A pA) // Use of raw type - this is bad, I know!
    {
        B lB = pA.mGetBList().get(0); // Compile error: Type mismatch: 
                                      // cannot convert from Object to test.B   

    }
}

If I declare

public test(A<?> pA)

the get() method returns a B as expected.

like image 541
jumar Avatar asked Oct 15 '22 12:10

jumar


1 Answers

+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);
like image 196
Alexander Pogrebnyak Avatar answered Oct 19 '22 01:10

Alexander Pogrebnyak