有人可以解释一下我的功能有什么问题吗,提前致谢: 我有这些类(class):
主要
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);
}
sumStrinToInt
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[])
最佳答案
基元和泛型不能混合。
将你的数组设置为包装类型Integer
,它将编译:
Integer[] outArr = new Integer[5];
但请注意,您必须初始化数组元素,否则它们将为 null
。
关于java - Java中泛型模板的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4096175/