Question

I am running into a problem where a conversion of a raw type to a type parametrized by wildcards results in an exception. Raw types are highly discouraged, but alternatives seem unwanted as well.

Consider the following classes:

public static abstract class A<T> { 
    T t;
    public abstract void add(T t2);
}
public static class C extends A<Double> {
    @Override public void add(Double t2) { t += t2; }
}
public static class D extends A<String> {
    @Override public void add(String t2) { t.concat(t2); }
}

And the following code:

public static void main(String[] args) {
    A<?>[] as = new A[2];
    as[0] = new C();
    as[1] = new D();
    for (A<?> a: as)
        a.add(a.t);      // results in a type mismatch exception
    for (A<?> a: as)
        insideFor(a);    // is not so neat
    for (A a: as)
        a.add(a.t);      // makes use of raw types
}
private static <T> void insideFor(A<T> a) {
    a.add(a.t);
}

What should I do?

Was it helpful?

Solution

The second way ("is not so neat") is the canonical way of doing it. This is called a capture helper. It takes advantage of capture to be able to introduce a "local" type variable. The helper method is usually made private so that outside code doesn't have to know it's there.

P.S. S is not used anywhere

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top