Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java function for int[], float[] or double[] array

Tags:

java

arrays

I want to write a Java function that will get as input either int[], float[] or double[]. The algorithm is exactly the same (some kind of a scalar product). How can I write a single function that will be able to handle all types of numeric arrays?

like image 551
Erel Segal-Halevi Avatar asked Oct 02 '11 09:10

Erel Segal-Halevi


2 Answers

There is no easy way to handle this in Java. You can:

  • Use Wrapper types (Integer[], Float[], Double[]) and have a function taking Number[] as an argument. Works since arrays are covariant in 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();
}

Note that this approach increases memory consumption significantly.


  • Convert int[] and float[] arrays to double[] and work with doubles all along. Preferably create overloaded versions of your method where the ones taking int[] and float[] are only doing the conversion and delegate to actual double[] implementation.

  • I believe Scala can handle this seamlessly as Java primitive types are semantically objects in Scala.

like image 82
Tomasz Nurkiewicz Avatar answered Sep 22 '22 10:09

Tomasz Nurkiewicz


You cannot code this in Java without either:

  • coding each case separately or,

  • using reflection for all operations on the array ... which is likely to be messy, fragile and an order of magnitude slower than an optimal solution.

The only common supertype of int[] float[] and double[] is Object, so there is no possibility of a solution using polymorphism over those types. Likewise, generics require that the type parameter is a reference type, and int, float and double are not reference types.

You either need to accept that you will have duplicate code, or change the representation type for the arrays; e.g. use Integer[] / Float[] / Double[] or Number[].

like image 25
Stephen C Avatar answered Sep 21 '22 10:09

Stephen C