上限有限泛型VS超类作为方法参数?

Som*_*one 7 java generics

据我所知,使用上限有限泛型并使用超类作为方法参数都接受相同的可能参数.哪个是首选,两者之间有什么区别?

上限有限泛型作为参数:

public <T extends Foo> void doSomething(T foo) {}
Run Code Online (Sandbox Code Playgroud)

超类作为参数:

public void doSomething(Foo foo) {}
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 6

这是一个上限的类型参数.使用创建下限super,您无法真正为类型参数创建.您不能拥有较低的有界类型参数.

如果你想要传递一个,那就会有所作为List<T>.因此,对于以下两种方法:

public <T extends Foo> void doSomething(List<T> foos) {}
public void doSomething(List<Foo> foo) {}
Run Code Online (Sandbox Code Playgroud)

对于给定的类:

class Bar extends Foo { }
Run Code Online (Sandbox Code Playgroud)

以下方法调用:

List<Bar> list = new ArrayList<Bar>();
doSomething(list);
Run Code Online (Sandbox Code Playgroud)

对第一种方法有效,但对第二种方法无效.第二种方法失败,因为a List<Foo>不是超类型List<Bar>,虽然Foo是超类型Bar.但是,第一种方法通过,因为类型参数T将被推断为Bar.