Search code examples
javaarraysgenericstypesprimitive

Is there a way to write generic Java methods that work with primitive array types?


EDIT: This question specifically regards Java primitive arrays. There are other questions that address writing generic methods for primitive scalar types, but arrays are sufficiently different to warrant keeping this question around for future reference (IMHO).

Consider the following Java method:

private int maxIndex(double[] values, double[] maxOut)
{
    int index = 0;
    double max = values[index];
    for (int i = 1; i < values.length; i++) {
        if (max < values[i]) {
            max = values[i];
            index = i;
        }
    }
    if (maxOut != null) {
        maxOut[0] = max;
    }
    return index;
}

Is there a way to write a generic version of this that will work with any of the primitive numeric types? As an example I tried the following:

private <T extends Comparable<T>> int maxIndexDoesNotWork(T[] values, T[] maxOut)
{
    int index = 0;
    T max = values[index];
    for (int i = 1; i < values.length; i++) {
        if (max.compareTo(values[i]) < 0) {
            max = values[i];
            index = i;
        }
    }
    if (maxOut != null) {
        maxOut[0] = max;
    }
    return index;
}

It doesn't work-- presumably because auto-boxing doesn't happen on arrays of primitive types. Not that I really want boxing, of course. What I'd really like is to be able to tell the compiler/runtime that T supports the '<' operator. Is there a way?


Solution

  • There is no way, because unlike autoboxing of individual values, there is no automatic conversion of collections/arrays of primitive element types to their wrapper object equivalent element types.