开发者

Java Properties and References -- I'm not getting what I expect

I'm a little embarrassed to ask this as I ought to know better, but here's what I've got.

I have an object "Pitcher" with an int property of "runsAllowed". I have an object Batter that has a property of "responsiblePitcher". I have an o开发者_Python百科bject Team that has a property "pitcher". When the batter reaches base:

Batter.responsiblePitcher = Team.pitcher;

All that's well and good. However, if we have a pitching change while the runner is on base, I set a new pitcher in Team.pitcher:

Team.pitcher = new Pitcher();

... and of course this changes the value of Batter.pitcher.

How should I be doing things differently such that the Batter.responsiblePitcher property continues to point to the pitcher who let him on base instead of pointing at whever is in the Team.pitcher property? Again, I feel like I ought to know this already ...

Thanks.


... and of course this changes the value of Batter.pitcher.

This is not true. Your problem lies somewhere else. Maybe you're actually changing the value like this:

Team.pitcher.changeSomeProperty(newValue);

Then this will indeed get reflected in the other references since it points the same instance.

Java is a pass reference by value language. The below example proves this:

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";
    }
}


Actually your assumption is not correct. Assigning Team.pitcher to a new value does not change Batter.pitcher. Batter.pitcher will still point to the old Pitcher instance.

The reason is that you are assigning a reference to an object, and not the object itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜