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

后端 未结 5 584
梦毁少年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:41

    In the first case you have two generic methods with type parameters named T, but these type parameters are different, so let's assign different names to them:

    public  List getList() { ... }
    public  void first() { ... }
    

    Then it works as follows:

    1. An element of List (that is object of type T) is assigned to the variable of type T, so everything works fine:

       List ret = new ArrayList();   
       T t1 = ret.get(0);
      
    2. Firstly, an object of type List is assigned to List. This statement works fine since type parameter E is inferred from the type of the left side of assignment, so T = E. Then it works as in the previous case:

       List list = getList();          
       T t2 = list.get(0);
      
    3. In this case you are trying to assign object of type E to the variable of type T, but E cannot be inferred and therefore assumed to be Object, so assignment fails:

        T t3 = getList().get(0);         
      

      You can fix this behaviour by binding E to T manually:

        T t3 = this.getList().get(0);
      

    In the case of generic class TestGenerics you don't have two independent type parameters, so T in both methods refers to the same type.

提交回复
热议问题