Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get an element from an array, edit it, then store it in another array, without altering the first array

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!

like image 955
Calin Avatar asked Mar 05 '26 09:03

Calin


2 Answers

You're going to have to create a new object.

The problem is the modifySomething call. 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 call modifySomething or 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:

Object tempObj = firstArray[3].clone();
tempObj.modifySomething();
secondArray[3] = tempObj;

The clone() method must return a new object divorced from the original but having identical properties.

like image 74
Borealid Avatar answered Mar 07 '26 23:03

Borealid


When you retrieve an element from your array, you have a reference to it. So if you modify it, the modification are shered through all the object's references.

In order to leave it intact, you should use some method like Object.clone() or create a new Object and use its constructor to initialize its fields.

like image 40
user278064 Avatar answered Mar 07 '26 23:03

user278064



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!