This method implements addition operations. The data on both sides of addition can be of the original type, encapsulation type of the original type, or even a class object.
If you have any ideas or are lacking in this algorithm, I 'd like to advise you.
For this reason, we first write a class for demonstration only, all of which are simple. And override the tostring method:
- Public Class B {
- Public String tostring (){
- Return "/" This is B /"";
- }
- }
The specific implementation of addition operations is as follows:
- Public static object CAL (Object O1, object O2 ){
- If (! (O1 instanceof number) |! (O2 instanceof number )){
- Return o1.tostring () + o2.tostring ();
- } Else {
- // For the type that generates the most suitable size, write it from the maximum to the minimum
- 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 (). Empty value () + new short (o2.tostring (). Empty value ());
- } 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 ());
- }
- }
- }
Perform a few test examples and output the results:
(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
String 56 and number 7 are added = 567
Number 7 and string 56 are added = 756
Character 7 and number 7 add = 77
Add character 7 and character 0 = 10
Add two strings 11 and 0 to 110