The first type: in main output, through reflection implementation
1 Public Static voidMain (string[] args)throwsException {2Integer A = 1;3Integer B = 2;4 Swap (A, b);5System.out.println ("a=" + A + "--------b=" +b);6 }7 8 Public Static voidSwap (integer i1, integer i2)throwsException {9 //How to change here, can not be output here, so that the main method of a, a, and a two value exchangeTenInteger temp =NewInteger (I1.intvalue ()); OneField I1value = I1.getclass (). Getdeclaredfield ("value"); AI1value.setaccessible (true); - I1value.set (I1, I2.intvalue ()); -Field I2value = I2.getclass (). Getdeclaredfield ("value"); theI2value.setaccessible (true); - i2value.set (I2, temp); - -}
//Second kind of simple exchange or something like that
1 /** 2 * Exchange Value Demo shows a simple example of space change time, and time-to-change space.3 * 4 * @authorWeep5 * 6 */ 7 Public classswapab {8 Public Static voidMain (string[] args) {9 //two kinds of value exchange, the spatial complexity of the intermediate variable is higher than without the intermediate variable, but the time complexity is less than the intermediate variable. Ten One //General write two-value exchange A intA = 100; - intb = 200; -SYSTEM.OUT.PRINTLN ("Initial value a=100 b=200"); the //Intermediate Variables - intC; - - //Copy to intermediate variable, temporarily save +c =A; - //assign the value of B to a. +A =b; A //assigns the initial value of a stored in C to the normal value exchange . atb =C; -System.out.println ("a =" + A + ", B =" +b); - //Do not use the middle variable notation -A = a +b; -b = A-b; -A = A-b; in -System.out.println ("a =" + A + ", B =" +b); to + //The second one does not need the intermediate variable, the operation, the efficiency is higher than the addition -A = a ^b; theb = a ^b; *A = a ^b; $ Panax NotoginsengSystem.out.println ("a =" + A + ", B =" +b); - the } +}
Java Exchange two digital locations