本文介绍了返回收藏<?扩展类型&gt; vs Collection&lt; Type&gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法有什么区别?

What is the difference between these two methods?

Collection<Type> getTypes();

vs

vs

Collection<? extends Type> getTypes();

Type是一个类还是一个接口?
特别是,当设计一个API时,哪个版本更受欢迎,为什么?

Does it matter if Type is a class or an interface?Especially, when designing an API, which version would be preferred and why?

推荐答案

Collection<Type> getTypes();

这里, getTypes()必须返回一个 Collection< Type> (例如 ArrayList< Type> 或 HashSet< Type> )。

Here, getTypes() must return a Collection<Type> (e.g. ArrayList<Type> or HashSet<Type>).

Collection<? extends Type> getTypes();

这里, getTypes() > > ArrayList< SubType> 或 HashSet< SubType> )。因此,从第一个变体返回的任何东西都可以从第二个变体返回。然而,在第二种情况下,您不知道集合的类型参数实际上是什么;你只知道它扩展了类型。

Here, getTypes() can return a Collection of anything that is or extends Type, (e.g. ArrayList<SubType> or HashSet<SubType>). So anything that can be returned from the first variant can also be returned from the second. In the second, however, you don't know what the type parameter of the collection actually is; you just know that it extends Type.

至于哪一个应该是首选的,重新尝试去做,更合理的是什么。请记住,如果您有< ;?扩展Type> ,你实际上并不知道?是什么,这有时会阻碍;更经常的是第一个变种更适合。您可以在基类中使用第二个变体,并在子类中使用更类似于第一个的类来覆盖它,例如:

As for which should be preferred, it really depends on what you're trying to do, and what makes more sense logically. Bear in mind that when you have <? extends Type>, you don't actually know what ? is, and this can be hindering at times; more often than not the first variant is more suitable. You can use the second variant in a base class and override it in subclasses with something that is more akin to the first, for instance:

@Override
Collection<SubType> getTypes() {
    ...
}

这篇关于返回收藏<?扩展类型&gt; vs Collection&lt; Type&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:19