monkjack monkjack - 5 months ago 25
Java Question

Java Generics with Wildcards Not Compiling

I'm having trouble understanding the finer points of Java generics with wildcards. specifically, why doesn't this compile.

public class Test {

abstract class Function<A, B> {
abstract B call(A a);
}

interface PropertyType {
String bubbles();
}

class Apartment implements PropertyType {
@Override
public String bubbles() {
return "bubbles";
}
}

public void invokeFunctionOnAList() {
List<Apartment> apts = new ArrayList<Apartment>();
functionLoop(apts, new Function<Apartment, String>() {

@Override
String call(Apartment a) {
return a.bubbles();
}
});
}

public void functionLoop(List<? extends PropertyType> list, Function<? extends PropertyType, String> t) {
for (PropertyType p : list) {
t.call(p);
}
}
}

Answer

Your compiler does not know if you are using same type in List and Function. Therefore you have to tell him this.

Try this:

public <C extends PropertyType>void functionLoop(
                         List<C> list, Function<C, String> t) {
  for (C p : list) {
    t.call(p);
  }
}
Comments