我们可以设计一个泛型函数,其中包括整数和字符串加法吗?

时间:2018-06-18 14:10:41

标签: java

class generic<T> {
    T a;
    T b;

    generic(T a, T b) {
        this.a = a;
        this.b = b;
    }

    public T sum() {
        return (a+b);
    }
}

//可以设计它,因为它将输入作为整数和字符串并且//将追加结果作为相同的返回类型。

3 个答案:

答案 0 :(得分:0)

您可以使用instanceof运算符。

您可以通过询问实例变量a或b是String还是Integer的实例来检查T的类型,并做出相应的决定。

class Generic<T>
{
    T a;
    T b;

    Generic(T a,T b) {
        this.a = a;
        this.b = b;
    }

    public T sum() {
        if (a instanceof String && b instanceof String) {
           // string concatenation e.g. return a + b + "\n";
        } else if (a instanceof Integer && b instanceof Integer) {
           // integer addition e.g. return a + b;
        }
        return null;
    }
}

请注意,在创建Generic对象时,您必须使用类类型而不是基本类型

更值得注意的是,您可以以比使用此Generic类更好的方式设计实现的组件。 (也许,继承?)

答案 1 :(得分:0)

不是那样但你可以这样做:

public class Adding{

 public static void main(String []args){
    String string = "12";
    Integer integer = 20;
    System.out.println(add(string, integer));
 }

 private static int add (Object a, Object b) {
     return toInt(a) + toInt(b);
 }

 private static int toInt (Object obj) {
     if (obj.getClass() == String.class) {
         return Integer.parseInt((String)obj);
     } else if (obj.getClass() == Integer.class) {
         return (Integer) obj;
     } else {
        //throw an exception
        return 0;
     }
 }

编辑:你也可以在这里使用你的通用类型

答案 2 :(得分:0)

你不需要写一个。只需使用现有的那样。

BiFunction<String, String, String> biStr = (s1, s2) -> s1 + s2;
BiFunction<Integer, Integer, Integer> biInt = (n1, n2) -> n1 + n2;

System.out.println(biStr.apply("One", "two"));
System.out.println(biInt.apply(10, 6));