回归收藏 vs Collection)

编程入门 行业动态 更新时间:2024-10-25 14:23:22
回归收藏<?(Returning Collection<? extends Type> vs Collection)

这两种方法有什么区别?

Collection<Type> getTypes();

VS

Collection<? extends Type> getTypes();

如果Type是一个类或一个接口,它是否重要? 尤其是,在设计API时,哪个版本更受欢迎,为什么?

What is the difference between these two methods?

Collection<Type> getTypes();

vs

Collection<? extends Type> getTypes();

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> )。

Collection<? extends Type> getTypes();

这里, getTypes()可以返回任何属于或扩展Type的Collection (例如, ArrayList<SubType>或HashSet<SubType> )。 因此,从第一个变体返回的任何东西都可以从第二个变体返回。 但是,在第二个中,您不知道集合的类型参数究竟是什么; 你只知道它扩展了Type 。

至于哪一个应该是首选的,这实际上取决于你想要做什么,以及什么使逻辑更合理。 请记住,当你有<? extends Type> <? extends Type> ,你实际上不知道什么? 是,这有时会阻碍; 更经常的是,第一个变体更适合。 您可以在基类中使用第二个变体,并在子类中使用与第一个类似的东西覆盖它,例如:

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

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

Collection<? extends Type> getTypes();

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.

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

更多推荐

本文发布于:2023-08-07 08:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462939.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:收藏   Collection

发布评论

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

>www.elefans.com

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