zoukankan      html  css  js  c++  java
  • java 传值和传引用

       关于传值和传引用看了不少帖子,谬误很多,甚至一些人都没测试过就直接猜结果写成博文,误人子弟,真是让人气愤!

       之所以很多人在这个问题上出错,实际上是对形式参数的不理解造成的。

       一个方法的形式参数,仅仅是在本方法内有效的,随着本方法在方法栈帧中被pop,所有的形式参数都要等着被垃圾回收了。

      例如我们这样子的代码:

        public static void main(String[] args){
            Test test  =new Test();
            String a = "11",b="22";
            test.swapPosition(a,b);
            System.out.println(a);
            System.out.println(b);
        }
        private void swapPosition(String a, String b){
            String t  = null;
            t =a;
            a = b;
            b = t;
        }

        输出结果是11,22;

        然后把String类型换成Integer类型:

    public static void main(String[] args){
            Test test  =new Test();
            Integer a = 11,b=22;
            test.swapPosition(a,b);
            System.out.println(a);
            System.out.println(b);
        }
        private void swapPosition(Integer a, Integer b){
            Integer t = 0;
            t =a;
            a = b;
            b = t;
        }

       结果依然输出结果是11,22;

       有人说你把对象换成基本类型,结果会传引用就变成了传值,

       那么笔者亲测:

    public static void main(String[] args){
            Test test  =new Test();
            int a = 11,b=22;
            test.swapPosition(a,b);
            System.out.println(a);
            System.out.println(b);
        }
        private void swapPosition(int a, int b){
            int t = 0;
            t =a;
            a = b;
            b = t;
        }

          结果依然输出结果是11,22  根本就不会变的;

          其实你换一种写法就明白了:

         

    public static void main(String[] args){
            Test test  =new Test();
            int a = 11,b=22;
            test.swapPosition(a,b);
            System.out.println(a);
            System.out.println(b);
        }
        private void swapPosition(int x, int y){
            int t = 0;
            t =x;
            x = y;
            y = t;
        }

        其实无论你怎么操作,操作的都是形式参数x,y,那么怎么实现交换位置呢?答案只有一种:绕开形式参数,不要用额外的方法:

       

    public static void main(String[] args){int a = 11,b=22;
    int t = 0;
    t =a;
    a = b;
    b = t; System.
    out.println(a); System.out.println(b); }

            然后输出值为22,11

        

  • 相关阅读:
    docker 部署aps.net MVC到windows容器
    docker 搭建私有仓库 harbor
    解决关于:Oracle数据库 插入数据中文乱码 显示问号???
    ionic cordova build android error: commamd failed with exit code eacces
    cordova build android Command failed with exit code EACCES
    Xcode 10 iOS12 "A valid provisioning profile for this executable was not found
    使用remix发布部署 发币 智能合约
    区块链: 编译发布智能合约
    mac 下常用命令备忘录
    JQuery fullCalendar 时间差 排序获取距当前最近的时间。
  • 原文地址:https://www.cnblogs.com/gangmiangongjue/p/4949452.html
Copyright © 2011-2022 走看看