简体   繁体   中英

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

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?

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.

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) {

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM