What is the difference between these 2 functions?
static void gPrint(List<? extends Number> l) { for (Number n : l) { System.out.println(n); } } static <T extends Number> void gPrintA(List<T> l) { for (Number n : l) { System.out.println(n); } }
I see the same output.
super is a lower bound, and extends is an upper bound.
6 Answers. Show activity on this post. Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ). The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?>
super E> , it means "something in the super direction" as opposed to something in the extends direction.
extends E means that it is also OK to add all members of a collection with elements of any type that is a subtype of E.
There is no difference in this case, because T
is never used again.
The reason for declaring a T
is so that you can refer to it again, thus binding two parameter types, or a return type together.
The difference is you can't refer to T
when using a wildcard.
You aren't right now, so there is "no difference", but here's how you could use T
to make a difference:
static <T extends Number> T getElement(List<T> l) { for (T t : l) { if (some condition) return t; } return null; }
This will return the same type as whatever is passed in. eg these will both compile:
Integer x = getElement(integerList); Float y = getElement(floatList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With