3

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?

1
  • On a sidenote: generics and arrays do not mix well since arrays are covariant, while generics are invariant. Commented Apr 12, 2018 at 14:08

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

A list of doubles is not the same as an array of doubles. Change the parameters to List<E> arr or actually pass it an array.

private <E> void print(List<E> list) {

If you want it to be the "most generic" then Iterable<E> should be the type of the parameter, since the Java for-each loop works for any implementer of this interface:

private <E> void print(Iterable<E> list) {

Comments

0

Probably the most flexible solution would be to use Iterable<E> and Arrays.asList.

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

private <E> void print(E[] list) {
    print(Arrays.asList(list));
}

You can then print almost anything and either one or the other method will be invoked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.