Clone an object (deep copy)

Asked

Viewed 184 times

2

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

I’m trying to build a method, which will save this text before any changes can be made to it. Obviously I started trying to make a vector of the type Text that stores the text before it is changed, however, because it is an object, when I make any alteration in the text by another method, this that is saved inside the vector is also changed.

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

But I do not understand how to implement this copy. Would it be possible for someone to help me? Abracos.

  • If you need to save the state of the text before it is changed, to have a shape undo the change, maybe the Pattern design Memento` help you.

1 answer

1

There are several ways to do this, but there is a lib called Commons-lang (very famous by the way), which makes it very easy.

Clone your object using the command:

SerializationUtils.clone(seuObjeto);

You can download the lib here: https://commons.apache.org/proper/commons-lang/download_lang.cgi

Or if you use Maven, Gradle or the like: http://mvnrepository.com/artifact/org.apache.commons/commons-lang3

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.