Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An issue with a generic method when passing an array as a parameter

Tags:

java

I have the following method that I want to pass arrays of different types:

    private < E > void print(E[] arr) {
        for(E s: arr) {
            System.out.println(s + "   ");
        }
    }

When I pass a List<Double> array to the print method, I get the following error:

The method print(E[]) in the type IAnalysisMocker is not applicable for the arguments (List<Double>)

Is there any suggestions of how to solve it?

like image 688
Adam Amin Avatar asked Apr 26 '26 16:04

Adam Amin


1 Answers

If you want to pass a list (or any iterable), then change the method signature to this:

private <E> void print(Iterable<E> iterable) {
    for(E s: iterable) {
        System.out.println(s + "   ");
    }
}

As the error says The method print(E[]) .. is not applicable for the arguments (List<Double>), you can't pass a List<E> when an array (E[]) is expected.

like image 62
xtratic - Reinstate Monica Avatar answered Apr 29 '26 05:04

xtratic - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!