【小家java】交换两个变量数值的方法(四种方法)

版权声明: https://blog.csdn.net/f641385712/article/details/81810789

推荐阅读

【小家java】java5新特性(简述十大新特性) 重要一跃
【小家java】java6新特性(简述十大新特性) 鸡肋升级
【小家java】java7新特性(简述八大新特性) 不温不火
【小家java】java8新特性(简述十大新特性) 饱受赞誉
【小家java】java9新特性(简述十大新特性) 褒贬不一
【小家java】java10新特性(简述十大新特性) 小步迭代


前言

本文主要介绍Java中可以交换两个变量的值的四种方法,可能开发者们在平时的coding中都有遇到过类似的情况,咋一看并不难。但本博文其实就是开开眼界而已,自己玩还行。

若你是一个注重代码设计效率,和优雅编程的人,或者本文能够和你一起探讨,产生共鸣。

四种方式

方式一:采用一个中间变量 优点:最简单最好理解的方式
  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

但是这里插一句,方式四,通过反射交换时,如果用Java8运行,就是上面的内容。如果用Java10运行如下:

交换前 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
交换前 x=10,y=20

很明显多了不少警告信息,因此可见Java9以后是加了很多安全性的东西的。若想了解更多,可以点击上面的 推荐阅读

猜你喜欢

转载自blog.csdn.net/f641385712/article/details/81810789