简体   繁体   English

Java未绑定的通配符泛型

[英]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 won't produce compiler warnings like using the raw type would 它们不会产生像使用原始类型那样的编译器警告
  • They give more type safety. 它们提供更多类型的安全性 For example, consider if Foo was List instead. 例如,考虑FooList 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除外),因为列表类型未知。

  • They document something completely different than a raw type, namely that Foo is typed on some unknown but specific type . 它们记录的内容与原始类型完全不同,即Foo是在某种未知但特定类型上键入的

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

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