2

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;
     }
Humza
  • 21
  • 1
  • 1
  • 2
  • You have to add the numbers as the same type, so you could do `x.intValue() + y.intValue();`. – Oli Mar 12 '15 at 13:14
  • 1
    you need to use some function of the generic type, just like @Oli said – JohnnyAW Mar 12 '15 at 13:19
  • This is kind of a silly (but nevertheless interesting) question. If you have two instances of some `T extends Number` then presumably the calling method knows what `T` is already, and could just add them appropriately. – Ian McLaird Mar 12 '15 at 13:56
  • Dont agree that this is a duplicate. The other question has nothing to do with generics. – Joe M May 24 '16 at 23:28

3 Answers3

6

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");
    }
 }
Ali Cheaito
  • 3,746
  • 3
  • 25
  • 30
  • 1
    might be better to throw `IllegalArgummentException` if it's not something you know how to cast, and just let the NPE happen if one of the arguments is `null`, but I like this otherwise. I agree it's sort of silly, though. – Ian McLaird Mar 12 '15 at 13:54
  • @IanMcLaird Good suggestion. Updated the answer to reflect it. – Ali Cheaito Mar 12 '15 at 13:56
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)

Fly
  • 21
  • 4
1

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...

Svend Hansen
  • 3,277
  • 3
  • 31
  • 50