有人可以解释我的功能有什么问题,提前谢谢: 我有这些课程:
public class Main {
public static void main(String[] args) {
String[] inArr = {"Hi", "Great", "Man", "Yeap", "Why"};
int[] outArr = new int[5];
Summer summing = new Summer();
outArr = summing.sum(inArr, 2, new sumStringToInt(), outArr); //here problem
for(int i = 0; i < outArr.length; i++){
System.out.println(outArr[i] + " ");
}
}
}
public class Summer{
public <X,Y> Y[] sum(X[] inArr, Y first, SumFunction<Y,X> f, Y[] outArr){
for(int i = 0; i < inArr.length; i++){
outArr[i] = f.op(first, inArr[i]);
first = outArr[i];
}
return outArr;
}
}
public abstract class SumFunction<Y,X> {
public abstract Y op (Y y, X x);
}
public class sumStringToInt extends SumFunction<Integer, String>{
public Integer op(Integer num, String s){
return s.length() + num;
}
}
我有一个错误:
The method sum(X[], Y, SumFunction<Y,X>, Y[]) in the type Summer is not applicable for the arguments (String[], int, sumStringToInt, int[])
答案 0 :(得分:2)
原始人和仿制药不混合。
创建包装类型Integer
的数组,它将编译:
Integer[] outArr = new Integer[5];
但请注意,您必须初始化数组元素,否则它们将为null
。
答案 1 :(得分:0)
您没有传递泛型参数,这导致它们是Object的类型。
summing.<String,Integer>sum(inArr, 2, new sumStringToInt(), outArr);
答案 2 :(得分:0)
在summing之前忘了<String,Integer>
。请参阅下面的代码:
public class Main { public static void main(String[] args) { String[] inArr = {"Hi", "Great", "Man", "Yeap", "Why"}; Integer [] outArr = new Integer [5];Summer summing = new Summer(); outArr = summing.<String,Integer>sum(inArr, 2, new sumStringToInt(), outArr); //here problem for(int i = 0; i < outArr.length; i++){ System.out.println(outArr[i] + " "); }
} }