我可以在java中添加两个通用值吗? [英] Can I add two generic values in java?
本文介绍了我可以在java中添加两个通用值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用了 .但是有没有其他方法可以添加两个通用值.可以这样吗?
i have used instance of . But is there any other way to add two generic values. Can it be done like this?
public static<T extends Number> T add(T x, T y){
T sum;
sum=x + y;
return sum;
}
推荐答案
你可以这样做来支持整数和双精度(和浮点数),尽管我没有看到它的真正价值
You could do this to support integers and doubles(and floats), though I don't see real value in it
public static<T extends Number> T add(T x, T y){
if (x == null || y == null) {
return null;
}
if (x instanceof Double) {
return (T) new Double(x.doubleValue() + y.doubleValue());
} else if (x instanceof Integer) {
return (T)new Integer(x.intValue() + y.intValue());
} else {
throw new IllegalArgumentException("Type " + x.getClass() + " is not supported by this method");
}
}
这篇关于我可以在java中添加两个通用值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文