这两种方法有什么区别?
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() { ... }更多推荐
发布评论