the following code has compilation error in the line of t3:
public List getList()
{
return new ArrayList();
}
public vo
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:
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);
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);
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.