【发布时间】:2012-01-11 12:11:39
【问题描述】:
在准备 SCJP(或现在已知的 OCPJP)考试时,我遇到了一些关于传递(引用)值和不变性的模拟问题。
我的理解是,当您将一个变量传递给一个方法时,您传递的是代表如何获取该变量的位的副本,而不是实际的对象本身。
您发送的副本指向同一个对象,因此如果该对象是可变的,您可以修改该对象,例如附加到 StringBuilder。但是,如果您对不可变对象执行某些操作,例如递增 Integer,则局部引用变量现在指向一个新对象,而原始引用变量仍然不会注意到这一点。
在这里考虑我的例子:
public class PassByValueExperiment
{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder();
sb.append("hello");
doSomething(sb);
System.out.println(sb);
Integer i = 0;
System.out.println("i before method call : " + i);
doSomethingAgain(i);
System.out.println("i after method call: " + i);
}
private static void doSomethingAgain(Integer localI)
{
// Integer is immutable, so by incrementing it, localI refers to newly created object, not the existing one
localI++;
}
private static void doSomething(StringBuilder localSb)
{
// localSb is a different reference variable, but points to the same object on heap
localSb.append(" world");
}
}
问题:是不是只有不可变对象才有这种行为,而可变对象可以通过传值引用来修改?我的理解是否正确,或者这种行为还有其他好处吗?
【问题讨论】:
-
private static void doSomething(StringBuilder localSb) { localSb = new StringBuilder("现在发生了什么"); }
标签: java immutability pass-by-value scjp ocpjp