pass by value vs pass by reference
程序员文章站
2022-04-24 14:19:14
...
pass by value
当参数是pass by value时,调用者和被调用者是有两个相同具有相同值的独立变量,被调用者修改了参数的值,调用者是看不到效果的。
pass by reference
当参数是pass by reference时,调用者和被调用者是使用一个相同的变量,如果调用者更改了参数的值,调用者是可以看到效果的。
Java参数传递
java都是pass by value, 看下面这个例子
public static void main(String[] args) {
String x = new String("ab");
change(x);
System.out.println(x); //ab
}
public static void change(String x) {
x = "cd";
}
这个例子和string的不可变性无关,只是因为Java是值传递
看另外一个例子
public static void main( String[] args ) {
Dog aDog = new Dog("Max");
foo(aDog);
// when foo(...) returns, the name of the dog has been changed to "Fifi"
aDog.getName().equals("Fifi"); // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// this changes the name of d to be "Fifi"
d.setName("Fifi");
}
这个表面一看看起来是传递的引用,实际上,Dog aDog是个变量,这个变量存储的是对象new Dog(“Max”)的地址,参数传递的时候传递的仍然是aDog的值,只是这个sDog的值又恰好是new Dog(“Max”)的地址而已。
上一篇: 关于包装类的知识总结
下一篇: 封包发送数据包
推荐阅读
-
php提示Call-time pass-by-reference has been deprecated in的解决方法[已测]
-
ubuntu 装配xampp,将php.ini文件中的allow_call_time_pass_reference=On后,打开网页提示下载保存网页不解析PHP
-
将要喷php5的Call-time pass-by-reference has been removed
-
php提示Call-time pass-by-reference has been deprecated in的解决方法[已测]_php实例
-
ubuntu 装配xampp,将php.ini文件中的allow_call_time_pass_reference=On后,打开网页提示下载保存网页不解析PHP
-
php提示Call-time pass-by-reference has been deprecated in的解决方法_PHP教程
-
将要喷php5的Call-time pass-by-reference has been removed
-
PHP Fatal error: Call-time pass-by-reference has been remove
-
php错误提示:Call-time pass-by-reference has been deprecated
-
php提示Call-time pass-by-reference has been deprecated in的_PHP