0
点赞
收藏
分享

微信扫一扫

写一个泛型方法,实现两个数字相加

泛型,Generic Type ,Generics

定义一个泛型,最重要的是什么?是类型呀,就是<T>这个标记。

写一个泛型方法,实现两个数字相加

static <T> T add(T a,T b) throws Exception {
if(a instanceof Integer){
return (T)Integer.valueOf(((Integer) a).intValue()+((Integer)b).intValue());
}else if(a instanceof BigDecimal){
return (T) ((BigDecimal) a).add((BigDecimal) b);
}else if(a instanceof Long){
return (T)Long.valueOf (((Long) a).longValue()+((Long) b).longValue());
}else {
throw new Exception("未实现该类型的加法"+a.getClass().getName());
}

}

测试:

public static void main(String[] args) throws Exception {
System.out.println(add(1,2));
System.out.println(add(1L,2L));
System.out.println(add(BigDecimal.TEN,BigDecimal.ONE));
System.out.println(add(1f,2f));
}

输出:

3
3
11
Exception in thread "main" java.lang.Exception: 未实现该类型的加法java.lang.Float
at com.clz.TestMain.add(TestMain.java:63)
at com.clz.TestMain.main(TestMain.java:72)

 

当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--​​buguge​​



举报

相关推荐

0 条评论