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

标签 java generics

<分区>

我试图理解为什么我们需要通配符——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());
}

}

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

最佳答案

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

通常,T 和 ?在泛型中用作占位符。即<?><T> .

用例:

<?>:它可以在开发人员希望允许特定实例的任何类型的对象时使用。

Example: List<?> listOfObject = new ArrayList<>(); Here in this case listOfObject can accept any kind of object which is extending the class Object

<T>:要使用的方法之一是复杂类型的对象 (DTO)。

i.e., Let's say if Class A can have same fields for different instances. However, there is one field which could be varied with the type of instances. Meanwhile, it could be the better approach to use Generics with

例子:

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.
   }
}

关于Java 泛型为什么需要通配符(问号)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49932682/

相关文章:

java - 在构造函数中处理 JDialog

java - Log4j 定义多个记录器

java - 是否有更好的 AtomicInteger 竞争条件比较功能?

c# - 通用节点的通用树 C#

java - 将抽象类中的泛型属性定义为实现类的类型

java - 当我们有可选行为时,正确的 restful API 设计是什么?

c# - 在与 Ninject 绑定(bind)时使用通用类型——这可能吗?

java - 使用反射根据泛型类的getClass创建实例

swift - 从 REST API 客户端返回一个通用的 swift 对象

java - 为什么很多项目只提供源码不提供jar包下载?