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

    

posted @ 2015-11-09 11:27  钢面公爵  阅读(218)  评论(0编辑  收藏  举报