schlafen schlafen - 27 days ago 7
Java Question

Method that creates new array on every call?

I am trying to create a method that creates a new array with a recognizable name every time that it's called. It's supposed to create arrays of size 2 that store two double values inside.

public static double[] newarray(double x, double y) {
double a[] = new double[2];
a[0] = x;
a[1] = y;
}


Basically something like this, but I would like the name of the array to be variable so that I can create multiple arrays like this with the same function.

For example the first array would be a, the next a1, a2, a3 and so forth.

Answer

Set up the function like this:

public static double[] newArray(double x, double y) {
    return new double[]{x, y};
}

Then call it like this:

double[] myArray1 = newArray(10d, 20d);
double[] myArray2 = newArray(3d, 4d);