I have encountered a problem in one of my Java projects, which causes bugs.
The problem sounds as following:
I have two arrays. Let’s name them firstArray and secondArray. Object in this case is a seperate class created by me. It works, the array can be filled with objects of that type.
Object[] firstArray= new Object[];
Object[] secondArray = new Object[];
Now, when I get an element out of the first array, edit it and then copy it in the second array, the object from the first array gets altered too.
tempObj = firstArray[3];
tempObj.modifySomething();
secondArray[3] = tempObj;
Whenever I do this, the (in this case) 3rd element(actually 4th) of the first array gets the modifications. I don’t want this. I want the first Array to remain intact, unmodified, and the objects I have extracted from the first array and then modified should be stored in the second so that the second array is actually the first array after some code has been run.
P.S. Even if I get the element from the first array with Array.get(Array, index) and then modify it, the element still gets modified in the first array.
Hopefully you understood what I wanted to say, and if so, please lend me a hand 🙂
Thank you!
You’re going to have to create a new object.
The problem is the
modifySomethingcall. When you do that, it alters the object on which it’s called. So if you’ve only got one object (even by two names), you can’t callmodifySomethingor they will both change.When you say
secondArray[3] = firstArray[3], you aren’t creating a new object: you’re just assigning a reference. Going through an intermediate temporary reference doesn’t change that.You’ll need code that looks like this:
The
clone()method must return a new object divorced from the original but having identical properties.