Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between <E extends Number> and <Number>?

Tags:

java

generics

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?

like image 868
unj2 Avatar asked May 05 '10 02:05

unj2


People also ask

What is the difference between List <? Extends T and List <? Super T >?

super is a lower bound, and extends is an upper bound.

What does<? extends mean in Java?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.

What is extend E Java?

extends E> means any object including E that is child of E .

What is the difference between and T in Java?

allows you to have a list of Unknown types, where as T requires a definite type. best answer +1 from me!


1 Answers

The first allows process of a List<Integer>, a List<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 of Number[], but a List<Double> is NOT a subtype of List<Number>. A List<Double>, however, is a List<? extends Number>.

There are good reasons for generics being invariant, but that's also why the extends and super type are often necessary for subtyping flexibility.

See also

  • Java Tutorials/Generics/Subtyping
    • Explains why generics invariance is a good thing
  • More fun with wildcards
    • Explains some uses of super and extends for bounded wildcards
  • Java Generics: What is PECS?
    • This discusses the "Producer extends Consumer super" principle
    • Effective Java 2nd Edition, Item 28: Use bounded wildcards to increase API flexibility
like image 62
polygenelubricants Avatar answered Sep 22 '22 13:09

polygenelubricants