问题
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;
}
回答1:
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");
}
}
回答2:
I would say you can't because Number abstract class don't provide "add" operation.
I think the best you can do with Number is to use the doubleValue() method and then use the + operation. But you will have a double return type (maybe you could cast to your concret class in the caller method)
public static <T extends Number> double add(T x, T y) {
double sum;
sum = x.doubleValue() + y.doubleValue();
return sum;
}
beware to null check
beware to loss of precision (ex: BigDecimal)
回答3:
EDIT: No, you can't actually do this, unfortunately, as you can't cast a Double to an Integer, for example, even though you can cast a double to an int.
I guess you could do something like:
public static<T extends Number> T add(T x, T y){
Double sum;
sum = x.doubleValue() + y.doubleValue();
return (T) sum;
}
Might make sense, at least for most subclasses of Number...
来源:https://stackoverflow.com/questions/29010699/can-i-add-two-generic-values-in-java