困惑,java是否在传递对象引用时使用按值调用或按引用调用? [英] Confused, whether java uses call by value or call by reference when an object reference is passed?

查看:102
本文介绍了困惑,java是否在传递对象引用时使用按值调用或按引用调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class program1 {

public static void main(String args []){

java.util.Vector vc = new java.util.Vector();

vc.add(111);
vc.add(222);

functioncall(vc);

vc.add(333);

System.out.println(vc);

}

public static void functioncall(java.util.Vector vc){

vc = null;

}
}

上述程序的输出为[ 111222333]。但是,当我运行以下程序时,输出为[333]。当我们传递引用时会感到困惑,无论是按值调用还是按引用调用,它是如何工作的?为什么

  public class program1 {

public static void main(String args []){

java.util.Vector vc = new java.util.Vector();

vc.add(111);
vc.add(222);

functioncall(vc);

vc.add(333);

System.out.println(vc);

}

public static void functioncall(java.util.Vector vc){

vc.removeAllElements();

}
}


解决方案

它传递了参考文献的



为了无耻地窃取我刚才在这里发布的类比,想象一下您使用的标识符是一张纸,上面写有地址。地址指向一个房子。



您可以更改房屋(例如,通过向向量添加对象或清除它),但您仍然保持相同一张纸,地址仍然带你到同一个房子。



如果你把矢量设置为null,你所做的只是擦掉地址。 / p>

这篇文章解释了它更多细节。


public class program1{

    public static void main(String args[]){

        java.util.Vector vc=new java.util.Vector();

        vc.add("111");
        vc.add("222");

        functioncall(vc);

        vc.add("333");

        System.out.println(vc);

    }

    public static void functioncall(java.util.Vector vc){     

        vc=null;    

    }
}

The output of above program is [111,222,333]. but, when I run the following program the output is [333]. Confused when we pass an reference , how it works whether it is call by value or call by reference? and why

public class program1{

    public static void main(String args[]){

        java.util.Vector vc=new java.util.Vector();

        vc.add("111");
        vc.add("222");

        functioncall(vc);

        vc.add("333");

        System.out.println(vc);

    }

    public static void functioncall(java.util.Vector vc){

        vc.removeAllElements();  

    }
}

解决方案

It passes the value of the reference.

To shamelessly steal an analogy I saw posted on here a while ago, imagine that each identifier you use is a piece of paper with an address written on it. The address points to a house.

You can change the house (for example, by adding objects to the vector or clearing it), but you're still holding the same piece of paper, and the address still takes you to the same house.

If you set the vector to null, all you're doing is rubbing out the address.

This article explains it in much more detail.

这篇关于困惑,java是否在传递对象引用时使用按值调用或按引用调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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