auto binding (type inference) of generic types by the compiler

后端 未结 5 657
梦毁少年i
梦毁少年i 2021-01-24 01:11

the following code has compilation error in the line of t3:

public  List getList()
{
    return new ArrayList();
}
public  vo         


        
5条回答
  •  没有蜡笔的小新
    2021-01-24 01:22

    I believe the answer from axtavt to be more correct than my own. Since mine contains a bit of speculation on my part and the other answer explains all the observed behaviour, cites relevant sources and makes general sense I ask you to read axtavts answer instead.

    For completeness sake, I will leave my original answer here. Just don't take it for absolute truth.


    The signature of java.util.List.get is as follows:

     public abstract java.lang.Object get(int arg0);
    

    get() returns Object, regardless of the parameterization of the type. That is why you cannot assign get(0) to a variable of type T. Even though you can (practically) guarantee that there will always be a T in the list, the interface just doesn't make that promise and the compiler cannot take your word for it.

    The problem appears to be with type-erasure. When you compile this code, it will work just fine:

    public  void someMethod(java.util.List list) {
        T s = list.get(0);
    }
    

    The compiler knows it's dealing with a List and can use the signature for List when compiling. It knows that get() will return a T and is perfectly happy. If you change the code to this it no longer works:

    public  List getList() {
        return new ArrayList();
    }
    
    public  void someMethod() {
        T s = getList().get(0);
    }
    

    The reason for this may be that when compiling the getList() method, the types are erased and it will now return a non-generic java.util.List type. get() on List returns Object and the compiler would no longer be aware that it used to be a List and will complain.

提交回复
热议问题