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

Deadly 提交于 2019-12-11 23:02:40

问题


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?


回答1:


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.




回答2:


No:(

But you can code-generate:)




回答3:


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;
}


来源:https://stackoverflow.com/questions/15237695/is-there-a-way-to-write-generic-java-methods-that-work-with-primitive-array-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!