java:使用原始类型作为方法参数会删除参数成员中的所有参数化类型信息

jum*_*mar 5 java generics

请解释为什么如果我在方法 test() 中使用原始类型 A ,我的类型列表中的 get() 方法返回一个对象而不是 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   

    }
}
Run Code Online (Sandbox Code Playgroud)

如果我声明

public test(A<?> pA)
Run Code Online (Sandbox Code Playgroud)

get() 方法按预期返回 B。

Ale*_*yak 2

有趣的测试用例+1。

看起来擦除会擦除所有内容,所以在这种情况下,你最终会得到。

public List mGetBList()

擦除List会导致public Object get( int ),当然,它不能被分配给B。

如果方法签名中没有强烈需要原始类型,请使用您提供的通用形式,否则将对象转换为B

B lB = (B) pA.mGetBList().get(0);
Run Code Online (Sandbox Code Playgroud)