简体   繁体   中英

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> List<? super E> , this defines the bounds for the return type. Can someone help me understand this with an example?

Thanks.

<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> List<? super E> - this is usually known as a contravariance. Check this out .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM