What is the difference between this method declaration:
public static <E extends Number> List<E> process(List<E> nums){
and
public static List<Number> process(List<Number> nums){
Where would you use the former?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first allows
processof aList<Integer>, aList<Double>, etc. The second doesn’t.Generics in Java are invariant. They’re not covariant like arrays.
That is, in Java,
Double[]is a subtype ofNumber[], but aList<Double>is NOT a subtype ofList<Number>. AList<Double>, however, is aList<? extends Number>.There are good reasons for generics being invariant, but that’s also why the
extendsandsupertype are often necessary for subtyping flexibility.See also
superandextendsfor bounded wildcardsextendsConsumersuper” principle