0

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?

3
  • Never mind that, you said arrays. Your code is still working with single value generics though. Commented Mar 6, 2013 at 2:08
  • 2
    Short answer: No. Long answer: Nooooooooooooo. Commented Mar 6, 2013 at 5:34
  • @Louis you made my day ahahahahaha Commented Mar 6, 2013 at 12:53

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought as much, but wanted to ask as all of the docs I've read on Java generics date from their introduction in Java 5. I was hoping that perhaps there was some additional capability introduced in later versions.
0

No:(

But you can code-generate:)

Comments

0

Using reflection, you can write a method that will work with primitive arrays or reference arrays, but you give up type safety in the process:

import java.lang.reflect.Array;

private int maxIndex(Object values, Object maxOut)
{
    int index = 0;
    Object max = Array.get(values, index);
    for (int i = 1; i < Array.getLength(values); i++) {
        if (((Comparable)max).compareTo(Array.get(values, i)) < 0) {
            max = Array.get(values, i);
            index = i;
        }
    }
    if (maxOut != null) {
        Array.set(maxOut, 0, max);
    }
    return index;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.