阅读了很多关于这个主题的堆栈溢出答案,我也阅读了很多博客。我可以肯定地得出结论,Java 是按值传递的。
但为了说服人们,我需要通过 ref. 证明某种语言。
那么有人可以给出一个通过引用传递的语言的实例吗?我们可以将 java 不是通过引用传递的例子联系起来。
最佳答案
So can someone give a live example of a language which is pass by reference by whose example we could relate that java is not pass by reference
引用传递与值传递的最佳示例是交换。
void swap(String a, String b) {
String c = b;
b = a;
a = c;
}
void main() {
String a = "A";
String b = "B";
swap(a, b);
System.out.println(a); // A
System.out.println(b); // B
}
在这种情况下,虽然变量 main.a 指向与 swap.a 相同的对象,但您有两个对字符串“A”的引用。
与 C# (IDE One)支持by-ref。
void Swap(ref string a, ref string b) {
string c = b;
b = a;
a = c;
}
void main() {
string a = "A";
string b = "B";
Swap(ref a, ref b);
Console.WriteLine(a); // B
Console.WriteLine(b); // A
}
在这种情况下,变量 main.a 和 swap.a 是相同的引用,因此对 swap.a 的更改也会发生在 main.a 上。
那么这和
有什么不同void swap(StringBuilder a, StringBuilder b) {
String a1 = a.toString();
String b1 = b.toString();
a.setLength(0);
a.append(b1);
b.setLength(0);
b.append(a1);
}
void main(){
StringBuilder a = new StringBuilder("A");
StringBuilder b = new StringBuilder("B");
swap(a, b);
System.out.println(a); // B
System.out.println(b); // A
}
在这种情况下,指向的对象会发生变化。例如:
public static void main(String... agv){
StringBuilder a = new StringBuilder("A");
StringBuilder b = new StringBuilder("B");
StringBuilder alsoA = a;
swap(a, b);
System.out.println(a); // B
System.out.println(b); // A
System.out.println(alsoA); //B
}
与 C# 中的对比 ( IDEOne )
void Main() {
string a = "a";
string b = "b";
string alsoA = a;
Swap(ref a, ref b);
Console.WriteLine(a); // B
Console.WriteLine(b); // A
Console.WriteLine(alsoA); // A
}
Java Ranch 有一个 good article如果您仍然不确定。
关于Java 显然是按值传递,但需要一些说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33932634/