You have to overload the testMethod(int, T[])
method to pass an int[]
array:
public static int testMethod(int rank, int[] elements) {
return elements[rank];
}
Otherwise, you need to meet requirements of T[]
, T extends Object
(which denies primitive types) and pass an Integer[]
array:
public static <T> T testMethod(int rank, T[] elements) {
return elements[rank];
}
Now you can pass either int[]
or Integer[]
:
final Integer i1 = testMethod(1, new Integer[]{1, 2, 4});
final int i2 = testMethod(1, new int[]{1, 2, 4});
Is there a way to make it work, while still using basic numeric types like int or double or float?
Unfortunately, only by method overloading. Have a look at the Arrays.binarySearch
methods (18 different signatures in there). Most of the signatures were designed only to cover all the types.
Would overloading require just copying the code from the main function though?
I am afraid, yes (with small type and naming changes). Find the difference :)
public static void parallelSort(long[] a, int fromIndex, int toIndex) {
rangeCheck(a.length, fromIndex, toIndex);
int n = toIndex - fromIndex, p, g;
if (n <= MIN_ARRAY_SORT_GRAN ||
(p = ForkJoinPool.getCommonPoolParallelism()) == 1)
DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
else
new ArraysParallelSortHelpers.FJLong.Sorter
(null, a, new long[n], fromIndex, n, 0,
((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
MIN_ARRAY_SORT_GRAN : g).invoke();
}
public static void parallelSort(float[] a, int fromIndex, int toIndex) {
rangeCheck(a.length, fromIndex, toIndex);
int n = toIndex - fromIndex, p, g;
if (n <= MIN_ARRAY_SORT_GRAN ||
(p = ForkJoinPool.getCommonPoolParallelism()) == 1)
DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0); // 1
else
new ArraysParallelSortHelpers.FJFloat.Sorter // 2
(null, a, new float[n], fromIndex, n, 0, // 3
((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
MIN_ARRAY_SORT_GRAN : g).invoke();
}
Is it a good practice to copy paste with little changes such code into several functions?
It is definitely not. But do we have another way?
You could say that primitive boxing might be an option:
final int[] ints = {1, 2, 4};
final Integer i3 = testMethod(1, Arrays.stream(ints).boxed().toArray(Integer[]::new));
But does a good API force users to convert their data to fit the given signatures?