Java通用模板中的问题 [英] problem in generic template in Java

查看:88
本文介绍了Java通用模板中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以请解释一下我的功能出了什么问题,在此先感谢: 我有那些课:

can somebody please explain what is wrong with my functions, thanks in advance: I have those classes:

 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的数组将编译:

Make your array of the wrapper type Integer and it will compile:

Integer[] outArr = new Integer[5];

但是请注意,您将必须初始化数组元素,否则它们将是null.

But note that you will have to initialize the array elements, because otherwise they'll be null.

这篇关于Java通用模板中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆