方法传对象参数 改变不了引用 懵...求大神

执行方法后不应该对象a ,b的指向交换吗?求指点!!!

public class Text16 {

    public static void main(String[] args) {
        Circle a = new Circle(1);
        Circle b = new Circle(2);
        method(a,b);
        System.out.println("一、a半径:"+a.radius+",b半径:"+b.radius);
    }
    public static void method(Circle x,Circle y){
        Circle tmp = x;
        x = y;
        y = tmp;
    }
    
}
class Circle{
    double radius;
    Circle(double x){
        radius = x;
    }
}
回复
阅读 4.1k
3 个回答

这个问题产生的根源是,对于java中参数传递的误区:

原始类型按值传递;对象按引用传递。

其实不然。请记住,

java中,无论是原始类型还是对象,都是按值传递的。

这里的“值”可以简单的理解为“对象或原始类型在内存中的地址”(并不准确)。

插播两个概念,‘按值传递’和‘按引用传递’:

Pass-by-value:
The actual parameter (or argument expression) is fully evaluated and
the resulting value is copied into a location being used to hold the
formal parameter's value during method/function execution. That
location is typically a chunk of memory on the runtime stack for the
application (which is how Java handles it), but other languages could
choose parameter storage differently.

Pass-by-reference:
The formal parameter merely acts as an alias for the actual parameter.
Anytime the method/function uses the formal parameter (for reading or
writing), it is actually using the actual parameter.

不知如何翻译才不会有误解,便不翻了。逃)

回过头来看题主的问题,当调用

method(a,b);

时,是将a和b的地址传入方法method,那么

public static void method(Circle x,Circle y){
        Circle tmp = x;
        x = y;
        y = tmp;
}

进入方法后,x初值为对象a的地址,y初值为对象b的地址;而进行交换后,只是将x指向了对象b的地址,y指向了对象a地址。而:

a和b的值并未交换。

好,现在再来看个例子:

Class User{
    private String name;
    .
    .
    .
}

public static void foo(User user){
    user.setName("Max");// AAA
    user = new User("Fifi");// BBB
    user.setName("Rowlf");// CCC
}

public static void main(String[] args){
     User basicUser = new User("Rover");
     foo(basicUser );
}

请问,‘AAA’、‘BBB’、‘CCC’这3行代码执行完后,对象basicUser的name分别是什么?

‘AAA’行:name为‘Max’;
‘BBB’行:name为‘Max’;
‘CCC’行:name为‘Max’;

请思考下原因。

Ps: 若有纰漏有误之处,欢迎批评指正。

java在函数参数传递上和C一致,都是"值传递"。只是在java中一个new出来的类得到的是一个引用,所以传的就是引用的值而已,实参是形参的一个引用值得拷贝,交换拷贝,形参并没有交换。

这道题的关键点其实是关于Java中Swap()方法的问题。Java中实现Swap的方式,有点复杂,只能通过返回值。

推荐问题
宣传栏