这可能吗?当然,如果您传入一个 double,那么除非专门使用强制转换“Integer”,否则将对象强制转换为 Integer 的任何类型的函数实现代码都将无法工作?我有一个类似的功能:
public static void increment(Object o){
Integer one = (Integer)o;
system.out.println(one++);
}
我不明白如何将其变成通用的 double ?我试过了
public static <E> void increment(E obj){
E one = (E)obj;
system.out.println(one++);
}
但它不喜欢它?
最佳答案
在 Java 中,方法参数是按值传递的。因此,增加方法参数不会改变调用者的值。因此,您必须返回新值:
double increment(double x) {
return x + 1;
}
或传递包含值的引用类型:
class MutableDouble {
double value;
}
void increment(MutableDouble d) {
d.value++;
}
在 Java 中,类型参数必须是引用类型,因此 double 不是类型参数的有效值。如果您想要原始类型,请考虑重载方法:
float increment(float f) {
return f + 1;
}
double increment(double d) {
return d + 1;
}
如果你真的想要泛型,你可以这样做:
@SuppressWarnings("unchecked")
<N extends Number> N increment(N n) {
if (n instanceof Double) {
return (N) (Double) (((Double)n) + 1);
} else if (n instanceof Float) {
return (N) (Float) (((Float)n) + 1);
} else if ( ...
// handle remaining cases
} else if (n == null) {
throw new NullPointerException();
} else {
throw new IllegalArgumentException("Unexpected number type: " + n.getClass());
}
}
不过这实在是太丑了。您想通过定义这样的方法来实现什么目的?可能有一个更简单的方法......
关于用于对整数、 double 执行计算的 Java 通用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695719/