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

查看:102
本文介绍了java - 方法传对象参数 改变不了引用 懵...求大神的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

执行方法后不应该对象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;
    }
}

解决方案

这个问题产生的根源是,对于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 - 方法传对象参数 改变不了引用 懵...求大神的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆