有没有办法编写通用的Java方法来处理基本数组类型? [英] Is there a way to write generic Java methods that work with primitive array types?

查看:138
本文介绍了有没有办法编写通用的Java方法来处理基本数组类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:这个问题特别关注Java原始数组。还有其他一些问题解决了为原始标量类型编写泛型方法的问题,但是数组完全不同以至于需要将这个问题留待将来参考(恕我直言)。



考虑以下Java方法:

pre $ code $ private $ maxIndex(double [] values,double [] maxOut)
{
int index = 0;
double max = values [index];
for(int i = 1; i if(max max = values [i];
index = i;


if(maxOut!= null){
maxOut [0] = max;
}
回报指数;





$ b有没有一种方法可以编写一个通用版本,原始数字类型?作为一个例子,我尝试了以下方法:

  private< T extends Comparable< T>> int maxIndexDoesNotWork(T [] values,T [] maxOut)
{
int index = 0;
T max = values [index];
for(int i = 1; i if(max.compareTo(values [i])< 0){
max = values [i ]。
index = i;


if(maxOut!= null){
maxOut [0] = max;
}
回报指数;
}

这不起作用 - 大概是因为自动装箱没有发生在基元类型的数组上。当然,我并不是真的想要拳击。我真正想要的是能够告诉编译器/运行时T支持'<'运算符。有没有办法?

解决方案

没有办法,因为与个别值的自动装箱不同,
。原始元素类型的数组添加到它们的包装对象等效元素类型。


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?

解决方案

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.

这篇关于有没有办法编写通用的Java方法来处理基本数组类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆