Reputation: 2317
I am new to Java generics and I am so confused.
I wrote this piece of codes, but I got error "Required type: capture of ? extends Number, Provided: Integer".
What went wrong?
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class TestGeneric {
// I want to create a list of Functions, and these Functions can have different input/output types than one another.
private List<Function<? extends Number, ? extends Number>> functions;
public TestGeneric() {
functions = new ArrayList<>();
}
public void addFunction(Function<? extends Number, ? extends Number> function) {
functions.add(function);
}
public void main(String[] args) {
TestGeneric testGeneric = new TestGeneric();
Function<Integer, Integer> hundredTimes = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) {
return integer * 100;
}
};
functions.add(hundredTimes);
Function<Double, Double> tenTimes = new Function<Double, Double>() {
@Override
public Double apply(Double o) {
return 10.0 * o;
}
};
functions.add(tenTimes);
System.out.println(functions.get(0).apply(Integer.valueOf(10)));
}
}
Upvotes: 1
Views: 290
Reputation: 88
The main problem is the definition of your functions list
private List<Function<? extends Number, ? extends Number>> functions;
I would try to use for your case:
private List<Function<Number, ? extends Number>> functions;
Then modify the other functions a little bit...
Function<Number, Integer> hundredTimes = new Function<Number, Integer>() {
@Override
public Integer apply(Number integer) {
return integer.intValue() * 100;
}
};
functions.add(hundredTimes);
Function<Number, Double> tenTimes = new Function<Number, Double>() {
@Override
public Double apply(Number o) {
return 10.0 * o.doubleValue();
}
};
functions.add(tenTimes);
System.out.println(functions.get(0).apply(Integer.valueOf(10)));
Using lambdas you could finally write:
functions.add( n -> n.intValue() * 100);
functions.add(n -> 10.0 * n.doubleValue());
System.out.println(functions.get(0).apply(10));
The problem is that the wildcard has an other meaning than you think by first thoughts. Using a wildcard means you use a specific type but you dont know it. At the time you want to add 10 as an int, the function asks for the specific type which is ?. So this will not work. Perhaps using generics on methods or on the class could solve your problem also depending on the use case. But change to Number should solve the problem.
Upvotes: 1