Java 如何在函数接口/lambda调用中传递对象
所以,我有一段代码Java 如何在函数接口/lambda调用中传递对象,java,generics,lambda,functional-interface,Java,Generics,Lambda,Functional Interface,所以,我有一段代码 public static void printStuff(Object[] stuffs, Function<?, String> func) { for(Object stuff : stuffs) { String stringStuff = func.apply(stuff); System.out.println(stringStuff); // or whatever, what is done
public static void printStuff(Object[] stuffs, Function<?, String> func) {
for(Object stuff : stuffs) {
String stringStuff = func.apply(stuff);
System.out.println(stringStuff);
// or whatever, what is done with that String is not relevant
}
// ...
所以我肯定需要我的东西是Object[],因为它是方法调用中不同类型的第一个常见超类
在编译方面,我得到:
MyClass.java:6: error: incompatible types: Object cannot be converted to CAP#1
String stringStuff = func.apply(stuff);
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
我的猜测是javac为我给函数的参数提供了一个解决方案,即使用:
public static <T> void printStuff(T[] stuffs, Function<T, String> func) {
for(T stuff : stuffs) {
// ....
一种解决办法是使用:
public static <T> void printStuff(T[] stuffs, Function<T, String> func) {
for(T stuff : stuffs) {
// ....
关于第一个代码:
public static void printStuff(Object[] stuffs, Function<?, String> func) {
for(Object stuff : stuffs) {
String stringStuff = func.apply(stuff);
System.out.println(stringStuff);
// or whatever, what is done with that String is not relevant
}
}
或以一般方式:
public static <U> void printStuff(U[] stuffs, Function<? super U, String> func) {
for(U stuff : stuffs) {
String stringStuff = func.apply(stuff);
System.out.println(stringStuff);
// or whatever, what is done with that String is not relevant
}
}
数组的类型必须等于函数的第一个类型参数或其子类。对于第一个代码:
public static void printStuff(Object[] stuffs, Function<?, String> func) {
for(Object stuff : stuffs) {
String stringStuff = func.apply(stuff);
System.out.println(stringStuff);
// or whatever, what is done with that String is not relevant
}
}
或以一般方式:
public static <U> void printStuff(U[] stuffs, Function<? super U, String> func) {
for(U stuff : stuffs) {
String stringStuff = func.apply(stuff);
System.out.println(stringStuff);
// or whatever, what is done with that String is not relevant
}
}
数组的类型必须等于函数的第一个类型参数或其子类。您不能公开静态void printtufft[]stuffs,Function func吗{和.nope,唉。看我的编辑你没有按照RC的建议更改你的签名。@Maaatt oops,读得太快了。确实有效-只要我不忘记更改内部for循环的类型。Daaang,我很确定类型变量数组是不可能的,尽管你不能公开静态void printtuff t[]stuff,Function func{和.nope,唉。看我的编辑你没有按照RC的建议更改你的签名。@Maaatt oops,读得太快了。确实有效-只要我不忘记更改内部for循环的类型。Daaang,我很确定类型变量数组是不可能的,尽管你已经搞定了。谢谢!你搞定了。谢谢!
public static void printStuff(Object[] stuffs, Function<Object, String> func)
public static <U> void printStuff(U[] stuffs, Function<? super U, String> func) {
for(U stuff : stuffs) {
String stringStuff = func.apply(stuff);
System.out.println(stringStuff);
// or whatever, what is done with that String is not relevant
}
}