Can I add two generic values in java? [duplicate]

瘦欲@ 提交于 2021-01-27 21:27:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!