-5

Can we write generic function in java to add different types of variable.

Example:

2+3 = 5(Integer addition)

"hi" + "I am here" = "hi I am here" (String addition)

  • Not anything like that. Generic parameter types can only be reference types. – Stephen C Jun 14 '18 at 06:29
  • 1
    If "generic" means "not type-specific", then you should look into dynamically typed languages. For the JVM, you can look into using Groovy. Java won't allow you to do that. – ernest_k Jun 14 '18 at 06:31
  • 1
    I really don't see how this question is a duplicate of the one at the given link. There may be many reasons to close this question, but not as a duplicate of that one IMO. – ernest_k Jun 14 '18 at 06:41
  • @ErnestKiwele Well, the question is pretty unclear. But the two examples given point to operator overloading. Given the poor quality of the question, the duplicate is fine. – GhostCat Jun 14 '18 at 06:47
  • 1
    Just because a question is poor is no reason to go for an irrelevant duplicate. That would be an abuse of the dupe hammer - closing an unclear question takes 5 votes for a good reason. – Erwin Bolwidt Jun 14 '18 at 06:48

1 Answers1

2

Yes - kind of, but not using Java generics. Something like this would be a start.

public Object add(Object... objects) {
    // Is there anything in the list that is not a `Number`?
    boolean allNumbers = true;
    for (Object object : objects) {
        if(!(object instanceof Number)){
            allNumbers = false;
            break;
        }
    }
    if(allNumbers) {
        Number[] numbers = new Number[objects.length];
        for (int i = 0; i < objects.length; i++) {
            numbers[i] = (Number)objects[i];
        }
        return add(numbers);
    } else {
        String[] strings = new String[objects.length];
        for (int i = 0; i < objects.length; i++) {
            strings[i] = String.valueOf(objects[i]);
        }
        return add(strings);
    }
}

public Number add(Number... numbers) {
    BigDecimal sum = new BigDecimal(0);
    for (Number number : numbers) {
        sum = sum.add(BigDecimal.valueOf(number.doubleValue()));
    }
    return sum;
}

public String add(String... strings) {
    StringBuilder sb = new StringBuilder();
    for (String string : strings) {
        sb.append(string);
    }
    return sb.toString();
}

public void test() {
    System.out.println(add(Integer.SIZE, BigInteger.TEN, BigDecimal.ROUND_UNNECESSARY));
    System.out.println(add(Integer.SIZE, BigInteger.TEN, BigDecimal.ROUND_UNNECESSARY, " - Hello"));
}

Prints:

49.0

32107 - Hello

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213