How could I specify a type that match both String and long?

Viewed 46

The situation is I have a function, and it calls Arrays.sort to sort given array. As Arrays.sort can sort both String and long, I want to use one single signature instead of two String[] array and long[] array.

I've tried something like Comparable[], it won't match long[]. I've also tried change long to Long. But the process of boxing and unboxing is significantly slowing down the sorting.

So I am wondering if there is a type I can specify that matches both of them? Or generally match all supported types of Arrays.sort?

2 Answers

The short answer is no, you can't.

Comparable is an interface and part of the object/class-system. A primitive, such as long, is not part of that system, only its boxed variant Long.

Unfortunately, you even can not solve this using generics, since they can also only be applied to classes, not to primitives (see Why don't Java Generics support primitive types?).

So until Project Valhalla (value types) releases, you will need to provide hard-coded variants for all 8 primitives (short, int, long, byte, char, float, double, boolean) if you want to avoid auto-boxing, there is no way around.

The Java API must do this too. You see overloaded methods of Arrays#sort for all relevant primitives and one generic overload for classes. From its documentation:

sort​(byte[] a)
sort​(char[] a)
sort​(double[] a)
sort​(float[] a)
sort​(int[] a)
sort​(long[] a)
sort​(short[] a)
sort​(Object[] a)
sort​(T[] a, Comparator<? super T> c)

The situation is I have a function, and it calls Arrays.sort to sort given array. As Arrays.sort can sort both String and long, I want to use one single signature instead of two String[] array and long[] array.

One can try method overloading like this.

public static void main(String [] args) {
    String [] strs = {"c", "x", "a", "d"};
    long [] ints = {4L, 343660L, 99L, 0L};
    Testing t = new Testing();
    t.sortMyArray(strs);
    t.sortMyArray(ints);
    System.out.println(Arrays.toString(strs)); // [a, c, d, x]
    System.out.println(Arrays.toString(ints)); // [0, 4, 99, 343660]
}

private void sortMyArray(long[] myArray) {
    Arrays.sort(myArray);
}

private void sortMyArray(String[] myArray) {
    Arrays.sort(myArray);
}
Related