【问题标题】:Java Generics why do we need wildcard (question mark)? [duplicate]Java 泛型为什么需要通配符(问号)? [复制]
【发布时间】:2018-09-30 15:24:46
【问题描述】:

我试图理解为什么我们需要通配符——Java 泛型中的问号,为什么我们不能只使用普通的单个字符 T 或 E 等作为类型?看下面的例子:

public class App {

public static void main(String[] args) {
    App a = new App();
    List<String> strList = new ArrayList<String>();
    strList.add("Hello");
    strList.add("World");
    List<Integer> intList = new ArrayList<Integer>();
    intList.add(1);
    intList.add(2);
    intList.add(3);

    a.firstPrint(strList);
    a.firstPrint(intList);

    a.secondPrint(strList);
    a.secondPrint(intList);
}

public <T extends Object> void firstPrint(List<T> theList) {
    System.out.println(theList.toString());
}

public void secondPrint(List<? extends Object> theList) {
    System.out.println(theList.toString());
}

}

结果是一样的,尽管通配符版本更简洁。这是唯一的好处吗?

【问题讨论】:

  • 通配符表示“任何类型”。 extends Object 在这两种情况下都是多余的。
  • 谢谢@user202729。所以 不起作用,但是 有效。为什么不让那个“T”以同样的方式工作呢?
  • @shmosel 我知道。我只是用它来测试语法。当然,一切都是对象。
  • 那是另一个question
  • And... cmets 仅用于提出改进建议,不用于扩展讨论或提出其他问题。

标签: java generics


【解决方案1】:

“?”是否可以充当占位符,您可以在其中传递不同类型的对象。

通常,T 和 ?在泛型中用作占位符。即&lt;?&gt;&lt;T&gt;

用例:

&lt;?&gt;: 当开发人员希望允许任何类型的对象用于特定实例时,可以使用它。

示例:List&lt;?&gt; listOfObject = new ArrayList&lt;&gt;(); 在本例中 listOfObject 可以接受任何扩展 类对象

&lt;T&gt;: 使用复杂类型对象 (DTO) 的方法之一。

即,假设 A 类是否可以为不同的实例具有相同的字段。 但是,有一个字段可以随着类型的不同而变化 实例。同时,这可能是使用泛型的更好方法

例子:

public Class A<T> {

   private T genericInstance;

   private String commonFields;

   public T getGenericInstance() {
      return this.genericInstance;
   }

   public String getCommonFields() {
      return this.commonFields;
   }

   public static void main(String args[]) {

      A<String> stringInstance = new A<>(); // In this case, 
      stringInstance.getGenericInstance();  // it will return a String instance as we used T as String.

      A<Custom> customObject = new A<>();   // In this case, 
      customObject.getGenericInstance();    // it will return a custom object instance as we used T as Custom class.
   }
}

【讨论】:

  • 它们的意思不同。
  • “只允许你传递对象类型的列表”——还有哪些其他类型的列表?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 2012-03-20
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多