首页 > 解决方案 > 我们可以设计一个通用函数来完成整数和字符串的加法吗?

问题描述

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

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

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

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

标签: java

解决方案


您可以使用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 类更好的方式设计实现的组件。(也许,继承?)


推荐阅读