【发布时间】:2016-12-30 06:13:21
【问题描述】:
由于 java 是按值传递的。在下面的代码中,我们将值传递给 appendStringMethod 而不是引用,那么为什么在 main 方法中我们得到 HelloWorld 而不仅仅是在 main 中调用 appendStringMethod() 之后的 Hello。
public class test {
public static void main(String args[]) {
StringBuilder str = new StringBuilder("Hello");
appendStringMethod(str);
System.out.println(str);
}
static void appendStringMethod(StringBuilder s) {
s.append("World");
}
}
但是在下面的代码中,值不会交换。
public class Mock {
public static void main(String args[]) {
StringBuilder str1 = new StringBuilder("Hello");
StringBuilder str2 = new StringBuilder("World");
swap(str1, str2);
System.out.println(str1);
System.out.println(str2);
}
static void swap(StringBuilder s1, StringBuilder s2) {
StringBuilder s= s1;
s1=s2;
s2=s1;
}
}
【问题讨论】:
-
在Java中,参数是按值传递的,但所有的对象都是引用(或指针)。所以你通过值传递一个指向 s 的指针。
-
因为
StringBuilder的引用是一个副本,但是StringBuilder的实例是一样的。appendStringMethod正在处理与main方法相同的对象。 -
I believe that much of the confusion on this issue has to do with the fact that different people have different definitions of the term "reference". People coming from a C++ background assume that "reference" must mean what it meant in C++, people from a C background assume "reference" must be the same as "pointer" in their language, and so on. Whether it's correct to say that Java passes by reference really depends on what's meant by "reference".- Gravity
标签: java pass-by-reference pass-by-value pass-by-reference-value