简体   繁体   中英

Copying an object and changing it (in Java)

I'm having an odd problem that I haven't encountered before with copying objects in Java. So, I've written a class in my code called "State". This contains a few ints, a 2d array, a string and such...

So, for an instance of State called S, I want to make a copy of it called X (I do this simply by writing State X = S; ). Then I want to make changes to X, do some evaluations based on those changes and then just throw away X and keep using S. However, the problem I'm getting is that S seems to be getting the changes that I make to X. This seems odd to me, since I feel quite certain that I've done things like this before but never had this problem.

Any thoughts? (Thanks in advance)

I want to make a copy of it called X (I do this simply by writing State X = S; ).

That does not make a copy of the object.

Variables (of non-primitive types) in Java are references - they are not the objects themselves. By doing

State X = S;

you are not copying an object, you are just copying the reference - the result is that you now have two variables that are referring to the same object. If you modify the object through one reference, you'll see the changes also through the other reference.

One way to copy objects is by using the clone() method. For this to work, the class of the object that you are trying to copy must implement interface Cloneable . Another (and probably better) way is to create a copy constructor, and use it to copy the object:

public class State {
    public State(State other) {
        // initialize this object by copying content from other
    }
}

// Make a copy
State X = new State(S);

Your code is not creating a copy of the object. What you are doing there is creating a new reference and pointing it to the same object. Search for "how to clone an object in Java". Read up on the Cloneable interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM