Java 泛型为什么需要通配符(问号)?

3

我正在尝试理解为什么在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());
}

}

虽然通配符版本更为简洁,但结果是相同的。这是唯一的好处吗?

谢谢@user202729。所以<T super String>不行,但是<? super String>可以用。为什么就不能让"T"以同样的方式工作呢? - Yang
@shmosel 我知道。我只是用它来测试语法。当然,每个东西都是一个对象。 - Yang
这是另一个问题。 - user202729
@user202729 好的。可能当我们需要这样的东西时:默认空白forEach(Consumer <? super T> action) - Yang
一个区别是你可以在firstPrint的代码中引用T - Dawood ibn Kareem
显示剩余2条评论
1个回答

2

“?”是一个占位符,可以允许传递不同类型的对象。

通常,在泛型中使用T和“?”作为占位符。即<?><T>

使用情况:

<?>: 如果开发人员希望允许特定实例的任何类型的对象,则可以使用该操作符。

例如: List<?> listOfObject = new ArrayList<>(); 在这种情况下,listOfObject可以接受任何继承Object类的对象。

<T>: 用于复杂类型对象(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.
   }
}

它们的意思不一样。 - shmosel
只允许传递类型为对象的列表,还有哪些其他类型的列表? - Dawood ibn Kareem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接