您的位置:首页 > 其它

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

2009-01-07 12:09 302 查看
该方法实现的是加法运算。加法两边的数据可以是原始类型,或者是对原始类型的封装类型,甚至是一个class对象。

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

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

public class B {

public String toString(){

return "/"This is B/"";

}

}

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

public static Object cal(Object o1, Object o2) {

if ( !(o1 instanceof Number) || !(o2 instanceof Number) ) {

return o1.toString() + o2.toString();

} else {

//为产生最适合的大小的类型,从最大到最小写出来

if( (o1 instanceof Double) || o2 instanceof Double){

return (new Double(o1.toString()).doubleValue() + new Double(o2.toString()).doubleValue());

}else if( (o1 instanceof Float) || (o2 instanceof Float) ){

return (new Float(o1.toString()).floatValue() + new Float(o2.toString()).floatValue());

}else if( (o1 instanceof Long) || (o2 instanceof Long) ){

return (new Long(o1.toString()).longValue() + new Long(o2.toString()).longValue());

}else if( (o1 instanceof Integer) || (o2 instanceof Integer) ){

return (new Integer(o1.toString()).intValue() + new Integer(o2.toString()).intValue());

}else if( (o1 instanceof Short) || (o2 instanceof Short) ){

return (new Short(o1.toString()).shortValue() + new Short(o2.toString()).shortValue());

}else if( (o1 instanceof Byte) || (o2 instanceof Byte) ){

return (new Byte(o1.toString()).byteValue() + new Byte(o2.toString()).byteValue());

}else {

return (new Double(o1.toString()).doubleValue() + new Double(o2.toString()).doubleValue());

}

}

}

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

(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐