3

Ref: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html,

We have the method: public <U extends Number> void inspect(U u)

Why can't this be: public void inspect(Number n) ?

It achieves the same thing, whats the point of using the generics here?

  • Not sure about this specific case, but for functions that actually return something, public <U extends Number> U foo(U u) has the property of returning the type you put in, rather than the supertype. – KChaloux Mar 29 '16 at 13:48
  • 1
    This method doesn't return anything since it is void, right ? – killjoy Mar 29 '16 at 13:59
  • I guess it is useful when having Multiple Bounds (We can specify multiple types that can be input) – killjoy Mar 29 '16 at 14:03
  • My guess is that the potential benefits are that 1) the subtype doesn't have to get converted to the base type, and 2) whatever goes on inside the body of inspect() is looking at the "real" type instead of just Number which may lead to more intuitive behavior if a polymorphic or overriden method gets called. Maybe. – Ixrec Mar 29 '16 at 14:19
  • @lxrec: No, there is no "real type" in the body of the method. The called method does not know what U is. – user102008 Mar 29 '16 at 21:40
2

In this case, there is no difference -- both methods accept the exact same set of possible inputs. In general, when the type parameter is used only once, and as a parameter type, it is unnecessary -- the generics adds no flexibility that subtyping did not already provide. And when the two versions are equivalent you should prefer the non-generic version.

However, there are many situations when a generic type for a generic method is necessary and cannot be eliminated. For example:

  • When it is used in multiple places, including once as a type argument in a parameter of parameterized type:

    public <T> void foo(List<T> x, T y)
    
  • When it is used in multiple places, including as a return type:

    public <T> T foo(T x)
    
  • Or even once as a return type:

    public <T> List<T> foo()
    
  • When it has a recursive bound:

    public <T extends Comparable<? super T>> foo(T x)
    
  • etc.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.