Difference between ? and T i.e Unbounded Wildcard and T

I stumbled upon a function looking like this:

public void function(Class<?> clazz) {...}

What are the pros/cons of changing the method to:

public <T> void function(Class<T> clazz) {...}

Using “?” is the same as “any”, whereas “T” means “a specific type”. So, compare these interfaces:

public interface StrictClass<T> {
 public T doFunction(Class<T> class);
}

public interface EasyClass<T> {
 public > doFunction(Class<?> class);
}

Now, we can create classes:

public class MyStrictClass implements StrictClass<String> {
  public String doFunction(Class<String> stringClass) {
    //do something here that returns String
  }
}

public class MyEasyClass implements EasyClass<String> {
  public String doFunction(Class<?> anyClass) {
    //do something here that returns String
  }
}

todd.run is totally right on, but that’s only half the answer. There are also use cases for choosing <T> over <?> (or vice versa) that apply when you don’t add type parameter to the class that encloses the method. For example, consider the difference between

public <E extends JLabel> boolean add(List<E> j) {
    boolean t = true;
    for (JLabel b : j) {
        if (b instanceof JLabel) {
            t = t &amp;&amp; labels.add(b);
        }
    }
    return t;
}

and

public boolean add(List<? extends JLabel> j) {
    boolean t = true;
    for (JLabel b : j) {
        if (b instanceof JLabel) {
            t = t &amp;&amp; labels.add(b);
        }
    }
    return t;
}

The first method will actually not compile UNLESS you add an appropriate type parameter to the enclosing class, whereas the second method WILL compile regardless of whether the enclosing class has a type parameter. If you do not use <?>, then you are locally responsible for telling the compiler how to acquire the type that will be filled in by the letter used in its place. You frequently encounter this problem – needing to use ? rather than T – when attempting to write generic methods that use or need “extends” and “super.” A better but more elaborate treatment of this issue is on page 18 of Gilad Bracha’s Generics Tutorial (PDF). Also see this stack overflow question whose answer illuminates these issues.

Check out this stack overflow link for information about your second question: Java generics – type erasure – when and what happens. While I don’t know the answer to your question about the compile time difference between <?> and <T>, I’m pretty sure the answer can be found at this FAQ that erickson mentioned in that post.

Reference :

Leave a Comment