0

In an interview, I was asked to write a function using Generics that adds the numbers and Strings passed to it. The number could be Integer, Double, etc.

If 2 strings are passed to the function, it should append the strings. Finally, the added result should be returned.

I used Lambda as mentioned below.

public class WorkAround {
    public static void main(String[] args) {
        MyAdd myAdd = new MyAdd();
        System.out.println("Adding Integers: " + myAdd.add(1, 2, (a,b) -> a+ b));
        System.out.println("Adding Double: " + myAdd.add(1.2, 1.2, (a,b) -> a+ b));
        System.out.println("Adding String: " + myAdd.add("James ", "Bond", (a,b) -> a + b));
    }
}

class MyAdd {
    public <T> T add(T a, T b, BinaryOperator<T> operation) {
        return operation.apply(a, b);
    }
}

Output:

Adding Integers: 3
Adding Double: 2.4
Adding String: James Bond

But then, I was asked to achieve the same result with Generics alone. Something like the below code snippet.

public class Trial {
    public static void main(String[] args) {
        MyAdd myAdd = new MyAdd();
        System.out.println("Adding Integers: " + myAdd.add(1, 2));
        System.out.println("Adding Double: " + myAdd.add(1.2, 1.2));
        System.out.println("Adding String: " + myAdd.add("James ", "Bond"));
    }
}

class MyAdd {
    public <T> T add(T a, T b) {
        return a + b;
    }
}

Obviously, this did not work because of the following.

The operator + is undefined for the argument type(s) T, T

I found this thread the closet to my question. But that question did not handle Strings. Is there any other way that I might be missing?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Andy
  • 5,433
  • 6
  • 31
  • 38

1 Answers1

0

We have 2 cases, String or Number. This differentiation should be made. The following solves the problem.

import java.math.BigDecimal;

public class Trial {
    public static void main(String[] args) {
        MyAdd myAdd = new MyAdd();
        System.out.println("Adding Integers: " + myAdd.add(1, 2));
        System.out.println("Adding Double: " + myAdd.add(1.2, 1.2));
        System.out.println("Adding String: " + myAdd.add("James ", "Bond"));
    }
}

class MyAdd {
    public String add(String a, String b) {
        return a + b;
    }

    public <T extends Number> T add(T a, T b){
        return (T) new BigDecimal(a.toString()).add(new BigDecimal(b.toString()));
    }
}
maxemann96
  • 91
  • 1
  • 8
  • Thanks for your answer. I think the same result can't be achieved using Generics alone but could be achieved using either method overloading or using lambdas. – Andy Jul 19 '19 at 18:12