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?
There is no easy way to handle this in Java. You can:
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.
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[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With