一个通用的加法计算,适合所有类型 注:不用方法重载实现

该方法实现的是加法运算。加法两边的数据可以是原始类型,或者是对原始类型的封装类型,甚至是一个class对象。

大家有什么想法或者是该算法有什么欠缺的,还望指教。

 

为此我们先写一个类,只为做演示,所有很简单。并重写其中的toString方法:

  1. public class B {
  2.     public String toString(){
  3.         return "/"This is B/"";
  4.     }
  5. }

 

下面是加法运算的具体实现:

  1.     public static Object cal(Object o1, Object o2) {
  2.          if ( !(o1 instanceof Number) || !(o2 instanceof Number) ) {
  3.             return o1.toString() + o2.toString();
  4.         } else  {
  5.             //为产生最适合的大小的类型,从最大到最小写出来
  6.             if( (o1 instanceof Double) || o2 instanceof Double){
  7.                 
  8.                 return (new Double(o1.toString()).doubleValue() + new Double(o2.toString()).doubleValue());
  9.                 
  10.             }else if( (o1 instanceof Float) || (o2 instanceof Float) ){
  11.                 
  12.                 return (new Float(o1.toString()).floatValue() + new Float(o2.toString()).floatValue());
  13.                 
  14.             }else if( (o1 instanceof Long) || (o2 instanceof Long) ){
  15.                 
  16.                 return (new Long(o1.toString()).longValue() + new Long(o2.toString()).longValue());
  17.                 
  18.             }else if( (o1 instanceof Integer) || (o2 instanceof Integer) ){
  19.                 
  20.                 return (new Integer(o1.toString()).intValue() + new Integer(o2.toString()).intValue());
  21.                 
  22.             }else if( (o1 instanceof Short) || (o2 instanceof Short) ){
  23.                 
  24.                 return (new Short(o1.toString()).shortValue() + new Short(o2.toString()).shortValue());
  25.                 
  26.             }else if( (o1 instanceof Byte) || (o2 instanceof Byte) ){
  27.                 
  28.                 return (new Byte(o1.toString()).byteValue() + new Byte(o2.toString()).byteValue());
  29.                 
  30.             }else {
  31.                 
  32.                 return (new Double(o1.toString()).doubleValue() + new Double(o2.toString()).doubleValue());
  33.                 
  34.             }
  35.         }
  36.     }

 

做几个测试例子:并输出结果:

(11.2,new B() )= 11.2"This is B"
(7,new B() )= 7"This is B"
(new B(),7 )= "This is B"7
(new B(),11.2 )= "This is B"11.2
(new B(),new B() )= "This is B""This is B"
(11.2,11.69874)= 22.89874
(11,11.69874)= 22.69874
(11.69874,11)= 22.69874
(11,7)= 18
short a = 9990; (a,7)= 9997
float b = 10.2f; (b,7)= 17.2
byte c = 10;; ( c,7)= 17
(11151515151510L,7)= 11151515151517
字符串56和数字7相加= 567
数字7和字符串56相加= 756
字符7和数字7相加= 77
字符7和字符0相加= 10
两个字符串11和0相加= 110

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值