(Java)交换变量,哪种方法最快并使用最少的内存?

时间:2017-12-16 12:51:01

标签: java

假设我想互相交换变量。以下哪种解决方案速度更快,内存更少? 注意:这里只交换了2个变量,但想象我们要交换10亿个变量。

解决方案1:

public class Exc15 {
    public static void main(String[] args) {

        int c = 1;
        int d = 2;
        int e = c;
        System.out.println(c + " " + d);
        c = d;
        d = e;
        System.out.println(c + " " + d);
    }
}

解决方案2:

public class test {
    public static void main(String[] args) {

        int a = 3;
        int b = 4;                
        System.out.println(a + " " + b);
        a = a + b;
        b = a - b;
        a = a - b;
        System.out.println(a + " " + b);
        } 
}

0 个答案:

没有答案