/ ** * transmitted by the process of how the reference values of the two exchange numbers * * @author zhuliang * @date 2019/7/14 10:39 * / public class SwapValueDemo { public static void main (String [] args) throws Exception { A Integer =. 1 ; Integer B = 2 ; System.out.println ( "before exchanging = A" + + A ", B =" + ; B) the swap (A, B); System.out.println ( "after exchange = A "+ + A", B = "+ B); } / ** * number of errors in two exemplary switching * * @paramA * @param B * / Private static void falseSwap (A Integer, Integer B) { int TEMP = A; A = B; B = TEMP; } / ** * by reflecting the switching values of the two numbers * result * exchange before 1 = A, b = 2 * 2 = after the exchange A, b = 2 * Why is this so? * <P> * caching mechanism because there is integer * { @link Integer.IntegerCache.low = -128} * { @link Integer.IntegerCache.high} = 127 * Because a = 1, b = 2 * in int temp = a.intValue (); This line , the acquired value of 1 is present in the cache * in value.set (a, b); after this line, the value of a to 2 * a.intValue is because the basic data types, the address itself can represent value, resulting in just temp value also becomes a 2 * then call value.set (b, temp); time will be assigned to the 2 b the final result is a so * 2 = a, B = 2 * <P> * solve this problem there are two ways * 1 the values a, b is a number greater than transducer 127 or less than -128, so as to not We use the caching mechanism Integer * 2 used when the assignment to the new Integer temp manner, to obtain a new address * * @param a * @param B * / Private static void the swap (a Integer, Integer B) throws Exception { value Field, = Integer. class .getDeclaredField ( "value" ); value.setAccessible(true); // int temp = a.intValue(); Integer temp = new Integer(a.intValue()); value.set(a, b); value.set(b, temp); } }