我有点尴尬地问这个,因为我应该知道更好,但这就是我所拥有的。
我有一个对象“Pitcher”,其int属性为“runsAllowed”。我有一个对象Batter,其属性为“responsiblePitcher”。我有一个具有属性“投手”的对象团队。当击球手到达基地时:
Batter.responsiblePitcher = Team.pitcher;
一切都很好。但是,如果我们在跑垒员的基础上进行投球改变,我会在Team.pitcher中设置一个新的投手:
Team.pitcher = new Pitcher();
...当然这会改变Batter.pitcher的价值。
我应该怎么做不同的事情,以便Batter.responsiblePitcher属性继续指向让他在基地而不是指向Team.pitcher属性中的投手的投手?再一次,我觉得我应该知道这个......
感谢。
答案 0 :(得分:2)
...当然这会改变Batter.pitcher的价值。
事实并非如此。你的问题出在其他地方。也许你实际上正在改变这样的价值:
Team.pitcher.changeSomeProperty(newValue);
然后,这确实会反映在其他引用中,因为它指向同一个实例。
Java是按值语言的传递引用。以下示例证明了这一点:
import java.util.Arrays;
public class Test {
public static void main(String... args) {
String[] strings = new String[] { "foo", "bar" };
changeReference(strings);
System.out.println(Arrays.toString(strings)); // still [foo, bar]
changeValue(strings);
System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeReference(String[] strings) {
strings = new String[] { "foo", "foo" };
}
public static void changeValue(String[] strings) {
strings[1] = "foo";
}
}
答案 1 :(得分:1)
实际上你的假设是不正确的。将Team.pitcher
分配给新值不会更改Batter.pitcher
。 Batter.pitcher
仍将指向旧Pitcher
实例。
原因是您要分配对象的引用,而不是对象本身。