Java通用函数

时间:2018-06-14 06:27:12

标签: java generic-programming

我们可以在java中编写泛型函数来添加不同类型的变量。

示例:

2 + 3 = 5(整数加法)

“hi”+“我在这里”=“我在这里”(字符串添加)

1 个答案:

答案 0 :(得分:1)

是 - 有点但不使用Java泛型。这样的事情将是一个开始。

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"));
}

打印:

  

49.0

     

32107 - 你好