You do know that you can create arrays of variable size by using a variable as the array length?
public float[] newFloatArray(int size) {
float[] array = new float[size];
return array;
}
Filling the array can be done with a loop or using the JRE supplied Arrays class helper methods. You will need to handle the first and last index in the array separately:
public float[] newGolfArray(int size) {
float[] array = new float[size];
Arrays.fill(array, 1F);
array[0] = 4F;
array[size - 1] = 2F;
return array;
}
Answer from Durandal on Stack OverflowVideos
There is no easy way to handle this in Java. You can:
- Use Wrapper types (
Integer[],Float[],Double[]) and have a function takingNumber[]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[]andfloat[]arrays todouble[]and work with doubles all along. Preferably create overloaded versions of your method where the ones takingint[]andfloat[]are only doing the conversion and delegate to actualdouble[]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[].
Loop over it yourself.
List<Float> floatList = getItSomehow();
float[] floatArray = new float[floatList.size()];
int i = 0;
for (Float f : floatList) {
floatArray[i++] = (f != null ? f : Float.NaN); // Or whatever default you want.
}
The nullcheck is mandatory to avoid NullPointerException because a Float (an object) can be null while a float (a primitive) cannot be null at all.
In case you're on Java 8 already and it's no problem to end up with double[] instead of float[], consider Stream#mapToDouble() (no there's no such method as mapToFloat()).
List<Float> floatList = getItSomehow();
double[] doubleArray = floatList.stream()
.mapToDouble(f -> f != null ? f : Float.NaN) // Or whatever default you want.
.toArray();
You can use Apache Commons ArrayUtils.toPrimitive():
List<Float> list = new ArrayList<Float>();
float[] floatArray = ArrayUtils.toPrimitive(list.toArray(new Float[0]), 0.0F);