1

Suppose I have a bounded type parameter in a generic method (an example from the The Java™ Tutorials, http://docs.oracle.com/javase/tutorial/java/generics/bounded.html):

public static <U extends Number> void inspect(U u) {
}

Then, I can call using any Number subtype arguments:

inspect(1);
inspect(1.0);
inspect(1.0f);

However, this is just the same as having a method with a Number parameter:

public static void inspect2(Number u) {
}

inspect2(1);
inspect2(1.0);
inspect2(1.0f);

What would be the benefits using Bounded Type Parameters (extends) in generic methods?

Note that not like

List<Map<String, String>> vs List<? extends Map<String, String>> 

these generic methods do not require/need any subtype relationships.

Sung Kim
  • 8,417
  • 9
  • 34
  • 42

3 Answers3

0

In my opinion if you use the defined U type as parameter type there is no advantage.

It is only useful if you share it across multiple parameters (and/or return type). First example:

public static <U extends Number> U someFunc(U u) {
  U result = u; //do something else
  return result;
}

If you had Number instead of U you will loose the information of the type. With the U type, when you use it you can do something like this:

Long l = someFunc(1L);
Integer i = someFunc(2);

Without the U type you would have Number as return type.

Other example:

public static <U extends Number> void func(U u2, Class<U> u1) {
  //do something
}
Jmini
  • 9,189
  • 2
  • 55
  • 77
0

You problem is not well defined as you use the bounded parameter as the return type and try to test the behavior in the method parameter.

This is related to variance in generics see What is PECS (Producer Extends Consumer Super)?

Community
  • 1
  • 1
Gab
  • 7,869
  • 4
  • 37
  • 68
0

In this particular case, there is no difference, since the type parameter is just used in one place as a parameter type.

In more complicated cases, a type parameter is necessary. For some examples,

  • <U> U func(U x)
  • <U> void func(U x, List<U> y)
  • <U extends Comparable<U>> void func(U x)
newacct
  • 119,665
  • 29
  • 163
  • 224