简体   繁体   English

将数组作为参数传递时泛型方法的问题

[英]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: 当我将List<Double>数组传递给print方法时,我收到以下错误:

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. 正如错误所示The method print(E[]) .. is not applicable for the arguments (List<Double>) ,当期望数组( E[] )时,不能传递List<E>

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. 将参数更改为List<E> arr或实际将其传递给数组。

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: 如果您希望它是“最通用的”,则Iterable<E>应该是参数的类型,因为Java for-each循环适用于此接口的任何实现者:

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

Probably the most flexible solution would be to use Iterable<E> and Arrays.asList . 可能最灵活的解决方案是使用Iterable<E>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. 然后,您可以print几乎任何内容,并且将调用其中一个或另一个方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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