Cloning an object (deep copy)

2

Good evening. I'm working on a program that writes a text. Basically it is composed of a Text object which is a list of Paragrafo objects, which is a list of Sentencas objects which is a list of Words objects that are a list of Strings.

I'm trying to build a method, which saves this text before any changes are made to it. Obviously I started trying to make a text-type vector that stores the text before it is changed, but because it is an object, when I make any changes in the text by another method, the one that is saved inside the vector is also changed. >

I have researched and found this one of Deep Copy, which makes a kind of cloning of the object, thus not making a reference to it as the vector does, but rather allocating in memory a copy of the object, so the changes will not effects in this copy.

But I do not understand how to implement this copy. Could someone help me? Hugs.

    
asked by anonymous 17.09.2015 / 00:30

1 answer

1

There are several ways to do this, however there is a lib called commons-lang (very famous for that), which does it very easily.

Clone your object using the command:

SerializationUtils.clone(seuObjeto);

You can download the lib here: link

Or if you use maven, gradle, or the like: link

Cloning objects will only work if all objects being cloned implement the Serializible interface.

    
17.09.2015 / 02:40