Search code examples
javaarraysfunctionprimitive

Take Any Numeric Primitive Array in Function


I want to write a function that will take any numeric 2D array. Using Java's object types, this is easy, as I can do something like:

public void process2DArray(Number [][] array) {
    // processing...
}

However, it'd be much easier to use if I could expand this function take any primitives, although, as arrays aren't autoboxed, the following code doesn't work:

double [][] array = new double [][] {{1,2},{3,4}};
process2DArray(array); // cannot invoke on array type double[][]

This function is going to process all numbers in the same way.

The best way I can think of to solve this to create a function for each primitive type which converts the array to a Number [][] type, and then passes it to the function. This just seems a little clunky - is there a more elegant way?


Solution

  • There isn't an elegant way to do it if you want to keep your code efficient. Your suggested solution of having multiple methods converting the primitive arrays to Number[][] is very inefficient - it involves boxing all the primitive values of your arrays.

    That's why the JDK duplicates the same code for different primitive types.

    You can see examples in Arrays static methods. For example, it contains 14 sort methods for 7 different primitive array types.