Class A

private X x;

public Method(X x) {
this.x = x;
}

public void stuff() {
Method2 m2 = new Method();
m2.doThis(x);
}

Class B

public Method2() {
}

public void doThis(X x) {
X copyOfX = x;

// MAKE CHANGES TO copyOfX here
}

What happens is. When I make changes to the copyOfX in class B - the original also ends up being changed. I've been pulling my hair out for several hours trying to find wtf is going on and just had to end up asking.

Recommended Answers

All 6 Replies

copyOfX is not a copy of x - it's a reference that refers to the same object that x refers to.

If you want a copy, you need to explicitly create a copy, for example by invoking a copy constructor (assuming one is defined) like this:

X copyOfX = new X(x);

it isnt though... the doThis() method is in a different class. I left out some code because this is for explanation purposes. But I'll edit that stuff in now.

the doThis() method is in a different class

That doesn't change anything. doThis is still passed a reference to the object, and copyOfX still makes a copy of only the reference. All references still point to the same underlying object.

Ok. I tried what sepp2k said and still the same problem. Weird thing is though it only seemingly exists for one particular variable.

    public enum Stuff {

        blah, blue, blow
    };

    private Stuff[][] twoD;

    private int test;

public dostuff(int x, int y, Enum stuff) {
twoD[x][y] = stuff;
}

public void changeTest(int newTest) {
test = newTest;
}

I make a copy like you said. Then I do the above to methods dostuff and changeTest with both the copy and the original. The test values are different but the twoD array values are not.

If you can help me with this it would really make my daYy! so any ideas send them over!

Think its maybe something to do with the Enums?

It's not the enums, they're just like any other object for this purpose.
Java has primitives and references. Primitives are int, boolean, char, float etc - all have lower case names. References are used to refer to objects and arrays.
When you call a method Java passes a copy of the value. If that's a primitive you get a copy of its value, and you have no access to the original value. If that's a reference then you get a copy of the reference, and thus you do have access to the original object or array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.