AlokI AlokI - 22 days ago 6
Java Question

How <? extends T> and <? super T> in function arguments work in Java?

public static <T> void copy(List<? extends T>src,List<? super T>dest)
{
for(T t : src)
dest.add(t);
}


What I understand is src can be of anything of type T or its subclass and dest can be anything of type T or its super class.

But what I'm not understanding is that how the compiler knows which T to compare with ?

Answer

Consider the hierarchy Employee-->Manager-->SalesManager

ArrayList<Employee> emp=new ArrayList<Employee>;
ArrayList<Manager> mgr=new ArrayList<Manager>;
ArrayList<SalesManager> smgr=new ArrayList<SalesManager>;

Now if I do

copy(mgr,smgr);

? extends T says that T or its subtype

? super T implies that T or its super So mgr cannot be added to smgr because the check is smgr a super type of mgr fails.

Comments