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

What is the difference between these two 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 result.

+43
java generics
Jul 16 2018-12-12T00:
source share
4 answers

In this case, there is no difference, because T is never used again.

The reason for declaring T is because you can reference it again, thus linking two types of parameters or return type together.

+30
Jul 16 2018-12-12T00:
source share
β€” -

The difference is that you cannot refer to T when using a wildcard.

You are not now, so there’s no difference, but here is 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 everything that is passed. For example, they will be compiled:

 Integer x = getElement(integerList); Float y = getElement(floatList); 
+31
Jul 16 '12 at 1:15
source share

T is a limited type, i.e. whichever type you use, you should stick with this particular type, which extends Number , for example. if you pass a Double type to a list, you cannot pass a Short type to it, since T is of type Double , and the list is already limited to that type. In contrast, if you use ? ( wildcard ), you can use "any" type that extends Number (add both Short and Double to this list).

+4
Aug 17 '14 at 5:06
source share

When you use T, you can perform all the actions in the list. But when you use, you cannot complete the add.

T is the same as a reference to an object with full access
? - provide partial access

 static void gPrint(List<? extends Number> l) { l.add(1); //Will give error for (Number n : l) { System.out.println(n); } static <T extends Number> void gPrintA(List<T> l) { l.add((T)1); //We can add for (Number n : l) { System.out.println(n); } 
0
Apr 21 '16 at 13:07 on
source share



All Articles