Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/2770264/what-is-the-difference-between-e-extends-number-and-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...