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

 郭红飞2001 发布于 2022-10-25 11:05

执行方法后不应该对象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;
    }
}
3 个回答
  • 这道题的关键点其实是关于Java中Swap()方法的问题。Java中实现Swap的方式,有点复杂,只能通过返回值。

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

    2022-10-26 23:18 回答
  • 这个问题产生的根源是,对于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: 若有纰漏有误之处,欢迎批评指正。

    2022-10-26 23:18 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有