Java未绑定的通配符泛型 [英] Java unbound wildcard generics
本文介绍了Java未绑定的通配符泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Bar
类中使用通配符类型的优点是否完全忽略它们?
public class Foo< T> {}
public interface Bar {
public void addFoo(Foo<?> foo);
public Foo<?> getFoo(String name);
解决方案
有很多优点。 / p>
- 它们不会像使用原始类型那样产生编译器警告
-
更多的类型安全。例如,考虑
Foo
是不是List
。如果您使用List
而不是List <?>< / code>,您可以这样做:
myBar.getFoo(numbers)。add(some string);
即使列表只有假设包含
数
秒。如果您返回了List<?>
,那么您将无法向其添加任何内容(除null
- 它们记录与原始类型完全不同的内容,即
Foo
在某些未知但特定类型上键入。
Are there any advantages of using wildcard-type generics in the Bar
class over completely skipping them?
public class Foo<T> {}
public interface Bar {
public void addFoo(Foo<?> foo);
public Foo<?> getFoo(String name);
}
解决方案
There are multiple advantages.
- They won't produce compiler warnings like using the raw type would
They give more type safety. For example, consider if
Foo
wasList
instead. If you usedList
instead ofList<?>
, you could do this:myBar.getFoo("numbers").add("some string");
even if the list was only supposed to contain
Number
s. If you returned aList<?>
, then you would not be able to add anything to it (exceptnull
) since the type of list is not known.- They document something completely different than a raw type, namely that
Foo
is typed on some unknown but specific type.
这篇关于Java未绑定的通配符泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文