37

I'm learning Java generics and I ask myself this question.

What is the difference between these two method declarations?

public static void someMethod(List<? extends Number> numberList);

and

public static <E extends Number> void someMethod(List<E> numberList);
Smi
  • 13,850
  • 9
  • 56
  • 64
ZeDonDino
  • 5,072
  • 8
  • 27
  • 28

4 Answers4

23

In the latter you have a reference to the type within the scope of someMethod, namely E. In the former you do not.

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
14

The main difference is that the latter is a generic method the former is not.

So for example in the latter method you can do something like this:

public static <E extends MyObject> void someMethod(List<E> someList) {
    E myObject = someList.iterator().next(); // this can actually lead to errors
    myObject.doSomething();                  // so treat it as an example
}

This means that you can substitute an arbitrary type E which conforms to the rule in the generic method declaration and be able to use that type in your method.

Be advised though that you should call the generic method with type arguments like this:

someClass.<MyArbitraryType>someMethod(someList);

You can find a nice overview of generic methods here.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
  • 1
    In java Se 7 and above you can call this `someClass.somemethod(someList);` i belive, don't have se7 compiler atm, please confirm? – ZeDonDino Feb 20 '13 at 12:22
  • 1
    I don't have se7 compiler atm either. – Adam Arold Feb 20 '13 at 12:23
  • Thanks for the explanation. But why would I want E? With the former version I can do `for(Number numb: numberList) { numb.anyMethodOfNumber(); }` Isn't it the same? – Boss Man Jul 01 '15 at 00:29
5

With the second version you can do something like:

public static <E extends Number> void someMethod(List<E> numberList) {
  E number = numberList.get(0); 
  numberList.add(number);
}

This isn't possible with the first version.

Landei
  • 54,104
  • 13
  • 100
  • 195
2

Using the first method declaration will not allow you to add anything new to the list. For example this will not compile.

public static void someMethod(List<? extends Number> numberList, Number number) {
    numberList.add(number);
}

while the second allows you to do this:

public static <T extends Number> void someMethod(List<T> numberList, T number) {
    numberList.add(number);
}
GabrielBB
  • 2,479
  • 1
  • 35
  • 49
Denis Rosca
  • 3,409
  • 19
  • 38