有没有办法编写通用的Java方法来处理基本数组类型? [英] Is there a way to write generic Java methods that work with primitive array types?
问题描述
考虑以下Java方法:
pre $ code $ private $ maxIndex(double [] values,double [] maxOut)
{
int index = 0;
double max = values [index];
for(int i = 1; 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屋!