benz benz - 3 months ago 9
Java Question

Deciphering Generics Syntax

I am reading through a question where the signature of the method is given below

public static <E extends CharSequence> List<? super E> doIt(List<E> nums)


I am unable to decode the syntax. I am very fresh in generics and unable to understand
this part. Doesn't the first part <
E extends CharSequence>
tells what E should be, both
for as an argument and as a return type. But i do see
List<? super E>
, this defines the
bounds for the return type. Can someone help me understand this with an example?

Thanks.

Answer
<E extends CharSequence>

tells that E will be a subtype of CharSequence. This tells the compiler that the type argument that will be passed to this method will either be a CharSequence or a sub type of that type. This type of bound is known as a parameter bound. I have written an article on this topic, you can check it out if you like.

List<? super E>

tells that this method will return a List of elements whose type will be either E or its super type.

So, all of the following types could be returned from your doIt method -

// trivial one.
return new ArrayList<E>();

// If F is a super type of E, then the following line is valid too.
return new ArrayList<F>();

// The following will also be valid, since Object is a super type of all
// other types.
return new ArrayList<Object>();

List<? super E> - this is usually known as a contravariance. Check this out.