Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic method parameter type inside brackets vs. outside brackets

Tags:

Is there any difference between:

static void findMax(LinkedList<? extends Number> list){...} 

and:

static <T extends Number> void findMax(LinkedList<T> list){...} 

Since both work, I'd like to know if there's any big difference between the two and which is advised.

like image 335
Paz Avatar asked Jul 03 '13 13:07

Paz


2 Answers

The main difference is that in the second version you can access the type T whereas in the first one you can't.

For example, you might want to return something linked to T (e.g. returning T instead of void):

static <T extends Number> T findMax(LinkedList<T> list){...} 

Or you might need to create a new list of Ts:

static <T extends Number> void findMax(LinkedList<T> list){     List<T> copyAsArrayList = new ArrayList<> (list);     //do something with the copy } 

If you don't need access to T, both versions are functionally equivalent.

like image 135
assylias Avatar answered Sep 16 '22 19:09

assylias


The first one should be used if you just care that findMax accepts a list that meets certain criteria (in your case a List of type that extends Number).

static Number findMax(LinkedList<? extends Number> list) {     Number max = list.get(0);     for (Number number : list) {         if (number > max) {             max = number;         }     }     return max; } 

This method returns Number. For example, this might be a problem if you have a class of your own that extends Number and has some special methods that you would like to use later on the result of this method.


The second one should be used when you plan to use exact type T in the method body, as a method parameter or as a return type of the method.

static <T extends Number> T findMax(LinkedList<T> list, T currentMax) {     T max = currentMax;     for (T number : list) {         if (number > max) {             max = number;         }     }     return max; } 

Conclusion:

Functionally, they are pretty much equivalent except that list with an unknown type (?) cannot be modified.

like image 41
darijan Avatar answered Sep 16 '22 19:09

darijan