Problem in generic pattern in Java

can someone explain what is wrong with my functions, thanks in advance: I have these classes:

Main

 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] + " ");
            }

        }
    }

summer

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;
    }
}

sum function

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;
    }
}

I have an error:

The method sum(X[], Y, SumFunction<Y,X>, Y[]) in the type Summer is not applicable for the arguments (String[], int, sumStringToInt, int[])
0
source share
3 answers

Primitives and generics do not mix.

Create your shell type array Integerand it will compile:

Integer[] outArr = new Integer[5];

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

+2
source

You do not pass a generic argument, and that means they are a type of object.

summing.<String,Integer>sum(inArr, 2, new sumStringToInt(), outArr); 
0
source

<String,Integer> summing.sum, . :

public class Main {public static void main (String [] args) {String [] inArr = {"Hello", "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] + " "); 
}   

}}

0
source

Source: https://habr.com/ru/post/1773706/


All Articles