小编Erm*_*mal的帖子

Why elements of typed List<> are cast to Object when used in the subclass

Can anyone explains why elements of typed List<> are cast to Object when used in a subclass?
This happens only when the parent class use generics.

In some how type of the class interferes with the type of the instance field.

public abstract class Parent<T> {
    protected List<String> myList = Arrays.asList("Hello", "World");

    void method1(){
        myList.get(0).substring(0, 1); //ok
    }
}


public class Child<T> extends Parent {
    void method2(){
        myList.get(0).substring(0, 1); //compilation error. myList.get(0) is of type Object and not …
Run Code Online (Sandbox Code Playgroud)

java generics types casting

2
推荐指数
1
解决办法
115
查看次数

标签 统计

casting ×1

generics ×1

java ×1

types ×1