简体   繁体   English

Java泛型:之间有什么区别 <?> 并跳过它?

[英]Java generics: what is the difference between <?> and skipping it?

Maybe it is silly question: Let say I have 也许这是一个愚蠢的问题:让我说

abstract class A<T> {
  List<Wrapper<T>> doStuff()
}

And I have class B extends A<String> and class C extends A<Integer> 我有class B extends A<String>class C extends A<Integer>

Now I want to have: 现在我想拥有:

List<A> aces = list with instances of B and C;

List<Wrapper> wrapperedItems = flattened list of lists returned from doStuff() on all items in aces

At this point I don't care what type is within Wrapper . 现在,我不在乎Wrapper类型。 And my question is: shall I use somewhere <?> or can I skip it? 我的问题是:我应该在<?>还是可以跳过? What is the difference? 有什么区别?

If you use List<Wrapper<?>> , you will be able to get objects out of the list, but you will not be able to add new items. 如果使用List<Wrapper<?>> ,则可以从列表中删除对象,但不能添加新项目。 The wildcard essentially correcponds to a type that is different from any other type, including other wildcards. 通配符实质上对应于与任何其他类型(包括其他通配符)不同的类型。

If you use List<Wrapper> , you will be able to both get list items and add new ones, but the onus is now up to you to guard for improper type casts. 如果使用List<Wrapper> ,则既可以获取列表项又可以添加新项,但是现在您有责任保护类型转换是否正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM