【问题标题】:Why the first swap attempt works, but the second doesn't work? [duplicate]为什么第一次交换尝试有效,但第二次无效? [复制]
【发布时间】:2019-04-13 19:44:30
【问题描述】:
package main;

public class Main {
    double radius;
    public Main(double newRadius) {
        radius = newRadius;
    }


    public static void main (String [] args) {
        Main x = new Main(1);
        Main y = new Main(2);
        Main temp;
        // try to swap first time
        temp = x;
        x = y;
        y = temp;
        System.out.println(x.radius + " " +  y.radius);
        x = new Main(1);
        y = new Main(2);
       // try to swap second time
        swap(x, y);
       System.out.println(x.radius + " " + y.radius);
    }
    public static void swap(Main x, Main y) {
        Main temp = x;
        x = y;
        y = temp;
    }

}

为什么第一次有效,第二次无效?第一个做了交换,但第二个没有。我正在传递对函数的引用。为什么这不起作用?

【问题讨论】:

标签: java oop


【解决方案1】:

您误解了如何传递引用,您创建了一个交换引用的范围,然后该范围结束。

尝试将字段的值存储在变量中,例如temp = x.radius 然后赋值给 y.radius。

之所以第一次起作用,是因为作用域是一样的。

【讨论】:

    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多