How to clone Object without modifying original?

I have an array of a class, that I want to clone. But if I modify the clone, the original gets modified to. Now is the question, how can i clone an array of classes without it modifying the original?

1 Like

Hi! Unfortunately that’s how it works in Java (and JavaScript too). That’s why classes implemented in Processing has copy() function to clone the object often called deep copy.

As far as I understand, you need to implement it by yourself to deep copy the object. This is an example of PVector

I think this is because you can have another object inside the object, and in that case having a deep copy is complicated. Perhaps the best practice would be to implement your own copy function that copies to the extent of what you need, and iterate the function for all the elements in the array (make sure you first create a new array, not to copy it from the original one).

yeah, that would be something like

class ClassName {

....
....

ClassName copy () {
   ClassName newElement = new ClassName(); 

   newElement.x= x; 
   newElement.y= y; 
   newElement.col= col; 
   // copy all properties you need here

   return newElement;  
}

}
//

Found a way to implement that already. Thx

1 Like