1

Hello I am working on a project in java and i need to do this : Heres the problem(using psuedo class names)

MyClass class1;
class1.addString("test");

then i would like to create a backup copy of that variable so when i call

class1.removeString();

I can access the copy and do class1 = copyVar; and have class1.getString() still equal to "test" Sorry I know this is a noob question never really learned how to do this

4

2 回答 2

1

There is no generic built-in way in Java to copy objects.

The closest you can get is Cloneable, but you have to implement that yourself.

于 2013-09-09T00:43:14.997 回答
1

You would need to override the clone method of object, so that when you call

MyClass class2 = class1.clone();

you copy out all the data in the class. This is usually accomplished by recursively calling clone on each of the other objects in the class and assigning it to a new instance.

于 2013-09-09T00:43:47.567 回答