[英]Java unbound wildcard generics
Are there any advantages of using wildcard-type generics in the Bar
class over completely skipping them? 在
Bar
类中使用通配符类型泛型相比完全跳过它们有什么优势吗?
public class Foo<T> {}
public interface Bar {
public void addFoo(Foo<?> foo);
public Foo<?> getFoo(String name);
}
There are multiple advantages. 有许多优点。
They give more type safety. 它们提供更多类型的安全性 For example, consider if
Foo
was List
instead. 例如,考虑
Foo
为List
。 If you used List
instead of List<?>
, you could do this: 如果您使用
List
而不是List<?>
,则可以执行以下操作:
myBar.getFoo("numbers").add("some string");
even if the list was only supposed to contain Number
s. 即使列表只应该包含
Number
秒。 If you returned a List<?>
, then you would not be able to add anything to it (except null
) since the type of list is not known. 如果您返回了
List<?>
,那么您将无法向其添加任何内容( null
除外),因为列表类型未知。
Foo
is typed on some unknown but specific type . Foo
是在某种未知但特定类型上键入的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.