首页 > 解决方案 > 是否可以在不更改方法主体的情况下编译通用可变参数方法?

问题描述

考虑这种通用交换方法:

package chapter06;

public class Ex05VarargsSwap {


public static <T> T[] swap (int i, int j, T... values) {


    T temp = values[i];
    values[i] = values[j];
    values[j] = temp;
    return values;
}


public static void main(String[] args) {

    Double[] result = Ex05VarargsSwap.swap(0,1, 1.5,2,3);

    /* The Error: Type mismatch: cannot convert from 
    * Number&Comparable<?>&Constable&ConstantDesc[] to Double[]
    */

    Double[] result2 = Ex05VarargsSwap.<Double>swap(0,1,1.5,2,3);
    /* The parameterized method <Double>swap(int, int, Double...) of type Ex05VarargsSwap is not 
    * applicable for the arguments (int, int, Double, Integer, Integer)
    */      

}

}

有没有办法让这段代码在不改变方法的情况下编译?

当然调用:Double[] result3 = Ex05VarargsSwap.swap(0, 1, 1.5, 2.0, 3.0);编译。

但我希望在不更改参数类型的情况下编译调用。(也许带有注释,或铸造......等)

标签: javagenericsvariadic-functions

解决方案


T...的意思array of T,同T[]。你不能有两种类型。在您的示例中,您尝试放入整数和双精度数,您不能T同时是整数和双精度数

你需要给出一个双打列表,所以不会这样做23你需要使用2dand 3dor or 2.0and3.0

像这样:

public static void main(String[] args) {
    Double[] result = Ex05VarargsSwap.<Double>swap(0, 1, 1.5, 2d, 3d);
}

推荐阅读