int [],float []或double []数组的Java函数

Ere*_*evi 5 java arrays

我想写一个Java函数,它将作为输入int[],float[]或者double[].算法完全相同(某种标量积).如何编写能够处理所有类型数值数组的单个函数?

Tom*_*icz 6

在Java中没有简单的方法来处理这个问题.您可以:

  • 使用包装类型(Integer[],Float[],Double[]),并有一个函数以Number[]作为参数.因为数组在Java中是协变的,所以可以工作:

public static void main(String[] args) {
    f(new Integer[]{1,2,3});
    f(new Float[]{1,2,3});
    f(new Double[]{1,2,3});
}

private static void f(Number[] numbers) {
    f[0].doubleValue();
}
Run Code Online (Sandbox Code Playgroud)

请注意,此方法会显着增加内存消耗.


  • 转换int[]float[]数组一直double[]使用双打.最好制定你的方法,其中的人服用的重载版本int[],并float[]只在做转换,并委托给实际double[]执行.

  • 我相信Scala可以无缝地处理这个问题,因为Java原始类型是Scala中的语义对象.


Ste*_*n C 5

如果没有:

  • 分别编码每个案例,或

  • 对阵列上的所有操作使用反射...这可能是凌乱,脆弱,比最佳解决方案慢一个数量级.

的唯一的公用超类型int[] float[]double[]Object,所以没有使用多态在这些类型的解决方案的可能性.同样地,泛型要求类型参数是一个引用类型,和int,floatdouble不引用类型.

您需要接受您将拥有重复的代码,或更改数组的表示形式; 例如使用Integer[]/ Float[]/ Double[]Number[].


Pet*_*rey 3

您可以编写一种方法来完成所有这些操作,但是,它的可读性和效率不会很高。您必须在通用解决方案和高效解决方案之间做出选择。

public static void main(String... args) throws IOException {
    int[] nums = new int[10*1000 * 1000];
    {
        long start = System.nanoTime();
        product2(nums);
        long time = System.nanoTime() - start;
        System.out.printf("Took %.3f seconds to take the product of %,d ints using an int[].%n", time / 1e9, nums.length);
    }
    {
        long start = System.nanoTime();
        product(nums);
        long time = System.nanoTime() - start;
        System.out.printf("Took %.3f seconds to take the product of %,d ints using reflections.%n", time / 1e9, nums.length);
    }
}

public static double product(Object array) {
    double product = 1;
    for (int i = 0, n = Array.getLength(array); i < n; i++)
        product *= ((Number) Array.get(array, i)).doubleValue();
    return product;
}

public static double product2(int... nums) {
    double product = 1;
    for (int i = 0, n = nums.length; i < n; i++)
        product *= nums[i];
    return product;
}
Run Code Online (Sandbox Code Playgroud)

印刷

Took 0.016 seconds to take the product of 10,000,000 ints using an int[].
Took 0.849 seconds to take the product of 10,000,000 ints using reflections.
Run Code Online (Sandbox Code Playgroud)

如果您只处理相对较小的数组,通用但效率较低的解决方案可能足够快。