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);
}
}
//可以设计这个,因为它接受整数和字符串的输入,并且 // 将附加结果作为相同的返回类型。
解决方案
您可以使用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 类更好的方式设计实现的组件。(也许,继承?)
推荐阅读
- excel - 突出显示与所选单元格对应的行/列的最快方法
- python - 如果我在尝试检索值时指定参数,则会出现“对象不可调用”错误
- java - 我如何正确引用此代码中的石头重量?
- javascript - 扩展 Object.setPrototypeOf() 与 Object.create
- amazon-web-services - 如何使用 Amazon ECS 运行 docker 任务 - 出现错误`STOPPED (CannotStartContainerError: Error response from dae)`
- ios - Phonegap/Cordova Barcodescanner 在最新的 ios 13 上再次全屏显示
- deployment - 如何将ansible字符串转换为浮点数并使用该值与浮点值进行比较
- git - VSCode:启用或禁用自上次 git 提交后修改的编辑器选项卡,使用修改后的选项卡颜色显示 git 状态
- python-3.x - 如何生成具有多列的数组行的组合?
- typescript - 绝对路径导入的 JS Cloud 函数错误