上界有界泛型VS超类作为方法参数? [英] Upper bounded generics VS superclass as method parameters?

查看:82
本文介绍了上界有界泛型VS超类作为方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

上限为通用参数:

  public< T extends Foo>作为参数的超类:



$ b

b $ b

  public void doSomething(Foo foo){} 


解决方案

这是一个上限的类型参数。下限是使用 super 创建的,对于类型参数您无法做到这一点。 不能有较低的有界类型参数。如果你想要传递一个 List< T> ,那就会有所作为。因此,对于以下两种方法:

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

对于给定的类:

  class Bar extends Foo {} 



以下方法调用:

 列表与LT;酒吧及GT; list = new ArrayList< Bar>(); 
doSomething(list);

适用于第一种方法,但不适用于第二种方法。第二种方法失败,因为 List< Foo> 不是超级类型的 List< Bar> ,尽管 Foo 是超级类型 Bar 。然而,第一种方法通过,因为那里的类型参数 T 将被推断为 Bar


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) {}

解决方案

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.

这篇关于上界有界泛型VS超类作为方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆