返回收藏<?扩展类型&gt; vs Collection&lt; Type&gt;

编程入门 行业动态 更新时间:2024-10-25 04:16:28
本文介绍了返回收藏<?扩展类型&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;

本文发布于:2023-11-09 06:07:45,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   收藏   lt   amp   Collection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!