Saturday, January 26, 2013

Java Generic < ? > vs < T >

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

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



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



When to use which one

There are also use cases for choosing 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 boolean add(List j) {
    boolean t = true;
    for (JLabel b : j) {
        if (b instanceof JLabel) {
            t = t && labels.add(b);
        }
    }
    return t;
}

and

public boolean add(List j) {
    boolean t = true;
    for (JLabel b : j) {
        if (b instanceof JLabel) {
            t = t && 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

No comments: