I wrote some code to test Supplier
and something went wrong but I don't know why.
here is the code:
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Client {
public static void main(String[] args) {
List<Integer> list = IntStream.range(1, 11).boxed().collect(Collectors.toList());
List<User> newList = addToList(list, User::new);
System.out.println(newList);
}
private static <T extends User> List<T> addToList(List<Object> srcList, Supplier<T> sp) {
if (srcList == null || srcList.isEmpty())
return null;
return srcList.stream().map(src -> {
T t = sp.get();
t.setAge(Integer.parseInt(src.toString()));
return t;
}).collect(Collectors.toList());
}
static class User {
Integer age;
public Integer getAge() {
return age;
}
void setAge(Integer age) {
this.age = age;
}
}
}
List<User> newList = addToList(list, User::new)
it has an error here says:
"Bad return type in method reference: cannot convert User to T".
Then I change the private method to below:
private static <T extends User, R> List<T> addToList(List<R> srcList, Supplier<T> sp) {
if (srcList == null || srcList.isEmpty())
return null;
return srcList.stream().map(src -> {
T t = sp.get();
t.setAge(Integer.parseInt(src.toString()));
return t;
}).collect(Collectors.toList());
}
and there is no error this time.
What's happened here? Every class should be the subclass of Object
, buy why can't I use 'Object' here?
I would appreciate it if someone help me.