public static void main(String[] args) { Integer a = 1; Integer b = 2; System.out.printf("a = %s, b = %s\n", a, b); swap(a, b); System.out.printf("a = %s, b = %s\n", a, b); } public static void swap(Integer a, Integer b) { // TODO 实现 }
// 特别提醒,这是错误的方式 // 特别提醒,这是错误的方式 // 特别提醒,这是错误的方式 public static void swap(Integer a, Integer b) { // TODO 实现 Integer temp = a; a = b; b = temp; }
public void test() { int shi_can = 0; testA(shi_can); } public void testA(int xing_can) { }
// 仅仅是一个java对象 public class IntType { private int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } // main方法 public class IntTypeSwap { public static void main(String[] args) { // CODE_1 IntType type1 = new IntType(); type1.setValue(1); IntType type2 = new IntType(); type2.setValue(2); // CODE_1 swap1(type1, type2); System.out.printf("type1.value = %s, type2.value = %s", type1.getValue(), type2.getValue()); swap2(type1, type2); System.out.println(); System.out.printf("type1.value = %s, type2.value = %s", type1.getValue(), type2.getValue()); } public static void swap2(IntType type1, IntType type2) { int temp = type1.getValue(); type1.setValue(type2.getValue()); type2.setValue(temp); } public static void swap1(IntType type1, IntType type2) { IntType type = type1; type1 = type2; type2 = type; } }
type1.value = 1, type2.value = 2 type1.value = 2, type2.value = 1
public static void swap1(IntType type1, IntType type2) { IntType type = type1; type1 = type2; type2 = type; }
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i (-IntegerCache.low)]; return new Integer(i); }
public static void main(String[] args) { Integer a = 1; Integer b = 2; System.out.printf("a = %s, b = %s\n", a, b); swap(a, b); System.out.printf("a = %s, b = %s\n", a, b); } public static void swap(Integer a, Integer b) { Integer temp = a; a = b; b = temp; }
public static void swap(Integer a, Integer b) { // TODO 实现 // 无解, }
private final int value; ... public Integer(int value) { this.value = value; }
public static void swap(Integer a, Integer b) { int temp = a.intValue(); try { Field value = Integer.class.getDeclaredField("value"); value.setAccessible(true); value.set(a, b); value.set(b, temp); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
a = 1, b = 2 a = 2, b = 2
public static void swap(Integer a, Integer b) { int temp = a.intValue(); try { Field value = Integer.class.getDeclaredField("value"); value.setAccessible(true); value.set(a, b); value.set(b, new Integer(temp)); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }