Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generic Primitive type n-d array

I have to pass a primitive 2d array to a filtering routine.The algorithm for filtering(median filter) is same irrespective of the type of the array.Is there a way to pass any type of array in a generic manner or should I overload the same same function with different array types.In the second case the same code will have to be repeated for different data types.

int[][] medianfilter(int[][] arr){ ... }
float[][] medianfilter(float[][] arr){ ... }

Is there a way to make the above code a generic one,instead of repeating the code for medianfilter in each an every overloaded function ?

like image 333
jayakumar Avatar asked Sep 05 '26 09:09

jayakumar


1 Answers

There is no good way to do this for primitive arrays, which is why all the library functions (such as java.util.Arrays) also have these duplicated methods.

You could define a method

Object[] medianfilter(Object[] arr); // note the missing dimension

and use reflection to find out the runtime type. This is what System.arraycopy is doing. But you then need to type-cast. Ugly.

int[][]  result = (int[][]) medianFilter( input );

Go with the duplicated methods.

like image 127
Thilo Avatar answered Sep 07 '26 22:09

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!