# 【小家java】交换两个变量数值的方法（四种方法）

#### 四种方式

###### 方式一：采用一个中间变量 优点：最简单最好理解的方式
  public static void main(String[] args) {
int x = 10, y = 20; //定义两个变量
System.out.println("交换前 x=" + x + ",y=" + y);
int temp = x;
x = y;
y = temp;
System.out.println("交换前 x=" + x + ",y=" + y);
}

###### 方式二：可以用两个数求和然后相减的方式 缺点:如果 x 和 y 的数值过大的话，超出 int 的值会损失精度。
public static void main(String[] args) {
int x = 10, y = 20; //定义两个变量
System.out.println("交换前 x=" + x + ",y=" + y);
x = x + y; //x = 30
y = x - y; //y = 10
x = x - y; //x = 20
System.out.println("交换前 x=" + x + ",y=" + y);
}

###### 方式三：利用位运算的方式进行数据的交换，思想原理是：一个数异或同一个数两次，结果还是那个数，而且不会超出int范围(最佳实现)
  public static void main(String[] args) {
int x = 10, y = 20; //定义两个变量
System.out.println("交换前 x=" + x + ",y=" + y);
x = x ^ y;  //x = 30
y = x ^ y;  //y = 10
x = x ^ y;  //x = 20
System.out.println("交换前 x=" + x + ",y=" + y);
}

###### 方式四：利用反射 最为麻烦，切效率低。完全炫技使用
 public static void main(String[] args) {
int x = 10, y = 20; //定义两个变量
System.out.println("交换前 x=" + x + ",y=" + y);
swap(x, y);
System.out.println("交换前 x=" + x + ",y=" + y);
}

private static void swap(Integer a, Integer b) {
int temp = a;
try {
Class clazz = a.getClass();
Field value = clazz.getDeclaredField("value");
value.setAccessible(true);
value.setInt(a, b);

value.setInt(b, temp);
} catch (Exception ex) {
ex.printStackTrace();
}
}


交换前 x=10,y=20



交换前 x=10,y=20
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.sayabc.boot2demo1.service.UserService (file:/D:/work/remotegitcheckoutproject/myprojects/java/boot2-demo1/target/classes/) to field java.lang.Integer.value
WARNING: Please consider reporting this to the maintainers of com.sayabc.boot2demo1.service.UserService
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release



©️2019 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie