Looking at the jdk implementatino of Dual pivot quick sort there is plenty of duplicate code for every type of array. For example:
ints:
static void sort(int[] a, int left, int right,
int[] work, int workBase, int workLen) {
// Use Quicksort on small arrays
if (right - left < QUICKSORT_THRESHOLD) {
sort(a, left, right, true);
return;
}
longs:
static void sort(long[] a, int left, int right,
long[] work, int workBase, int workLen) {
// Use Quicksort on small arrays
if (right - left < QUICKSORT_THRESHOLD) {
sort(a, left, right, true);
return;
}
Why not just use T[] a and benefiting from autoboxing?
This is done for performance reasons. Generic T[] cannot be used in place of an array of primitive ints or longs, so without an overload with int[] or long[] the users would be forced to use the generic that uses boxed Longs and Integers.
You would not be able to benefit from autoboxing here, either, because autoboxing is defined for individual primitives, not for arrays of primitives.
private static <T> void doSomething(T[] array){
...
}
public static void main (String[] args) throws java.lang.Exception {
doSomething(new String[10]); // Compiles fine
doSomething(new int[10]); // Compile-time error
}
Main.java:...: error: method doSomething in class ... cannot be applied to given types;
doSomething(new int[10]); ^ required: T[] found: int[]reason: inference variable T has incompatible bounds equality constraints: int upper bounds: Object where T is a type-variable: T extends Object declared in method doSomething(T[])
Even if you could, the processing would be a lot slower, and it would require a lot of additional memory, because wrapping large arrays of primitives could be expensive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With