Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upper bounded generics VS superclass as method parameters?

Tags:

java

generics

As far as I know, using an upper bounded generic and using a superclass as a method parameter both accept the same possible arguments. Which is preferred, and what's the difference between the two, if any?

Upper bounded generic as parameter:

public <T extends Foo> void doSomething(T foo) {}

Superclass as parameter:

public void doSomething(Foo foo) {}
like image 233
Someone Avatar asked Jan 27 '14 20:01

Someone


1 Answers

That's an upper bounded type parameter. Lower bounds are created using super, which you can't really do for a type parameter. You can't have a lower bounded type parameter.

And that would make a difference, if you, for example want to pass a List<T>. So, for the below two methods:

public <T extends Foo> void doSomething(List<T> foos) {}
public void doSomething(List<Foo> foo) {}

And for the given class:

class Bar extends Foo { }

The following method invocation:

List<Bar> list = new ArrayList<Bar>();
doSomething(list);

is valid for 1st method, but not for 2nd method. 2nd method fails because a List<Foo> is not a super type of List<Bar>, although Foo is super type of Bar. However, 1st method passes, because there the type parameter T will be inferred as Bar.

like image 191
Rohit Jain Avatar answered Sep 27 '22 22:09

Rohit Jain