1

Can someone please explain why we would ever use ? extends .... To me, it seems that I can always use the super type whenever I want to specify such a condition in my code. For example, ? extends Number can always be replaced with Number right?

Consider the following

public static double numberAdd(List<Number> list) {
    double sum = 0;
    for (Number x : list) {
        sum += x.doubleValue();
    }
    return sum;
}

vs.

public static double genericAdd(List<? extends Number> list) {
    double sum = 0;
    for (Number x : list) {
        sum += x.doubleValue();
    }
    return sum;
}

Both do the same thing^. Any reason why you would use the List<? extends Number> version?

mave_rick
  • 59
  • 8
  • 2
    What if you want to generically add a `List`? Try that with both, see what happens. – Andy Turner Jul 17 '18 at 07:41
  • The first method will only accept an argument of type `List`, the second one will accept any list whose type extends `Number` (`List`, `List` etc). – BackSlash Jul 17 '18 at 07:42
  • See [Difference between super T> and extends T> in Java](https://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java) - mine of information on this topic – jannis Jul 17 '18 at 07:46
  • Ok got it. Thanks a lot. This post https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po describes exactly what was the source of my confusion – mave_rick Jul 17 '18 at 07:47

1 Answers1

1

numberAdd(List<Number> list) will only accept a List<Number>.

genericAdd(List<? extends Number> list) will accept a List<Number> or a List<Integer> or a List<Double>, etc...

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thank you, I tried what you suggested and there's clearly a difference. the reason for this behavior is explained in this post https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po I'll mark your answer as accepted soon as it lets me – mave_rick Jul 17 '18 at 07:49