3

I am trying to understand why do we need the wildcard -- question mark in Java Generics, why can't we just use the normal single character T or E etc. as the type? Look at the following example:

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());
}

}

The result is same albeit the wildcard version is more concise. Is that the only benefit?

Yang
  • 39
  • 3

1 Answers1

2

The "?" is there to act as a placeholder where you are allowed to pass the different type of objects.

Normally, T and ? is used in generics as a placeholder. i.e <?> or <T>.

Use Cases:

<?>: It could be used while developer wants to allow any type of object for particular instance.

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

<T>: One of the approach to be used it complex type of Object (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

Example:

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.
   }
}
Abhishek Shah
  • 1,394
  • 1
  • 16
  • 25
kobs20
  • 125
  • 1
  • 8