Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics WildCard: <? extends Number> vs <T extends Number>

Tags:

java

generics

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.

like image 761
vikky.rk Avatar asked Jul 16 '12 01:07

vikky.rk


People also ask

What is the difference between list <? Super T and list <? Extends T?

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

What is the difference between T and in Java generics?

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<?>

What does <? Super E mean?

super E> , it means "something in the super direction" as opposed to something in the extends direction.

What does <? Extends E mean in Java?

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.


2 Answers

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.

like image 114
Thilo Avatar answered Oct 03 '22 06:10

Thilo


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); 
like image 28
Bohemian Avatar answered Oct 03 '22 07:10

Bohemian