Hum*_*mza 2 java generics addition
我已使用的实例。但是还有其他方法可以添加两个通用值。可以这样吗?
public static<T extends Number> T add(T x, T y){
T sum;
sum=x + y;
return sum;
}
Run Code Online (Sandbox Code Playgroud)
您可以执行此操作以支持整数和双精度(和浮点数),尽管我没有看到真正的价值
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");
}
}
Run Code Online (Sandbox Code Playgroud)