0

I have an Object A. I assign values from A to Object B. Object A is then changed, but I want to maintain the original values in Object B.

ObjectA a = getObjectAValues();

ObjectB b = new ObjectB();

b.setval(a.getValA());

//object A updated here

return b;

When I check the second object, it has the updated values, rather than the original value when I first assigned it. Any ideas how to get past this?

Makoto
  • 104,088
  • 27
  • 192
  • 230
helpme7766
  • 249
  • 5
  • 13
  • Not a dupe - that explains the mechanics but doesn't actually *answer* the question. – Makoto Dec 13 '18 at 17:36
  • I am not sure what you want to achieve, nor what is problem with current code. When you say "Object A is then changed" do you mean value of `a` or `a.getValA()` (which also is confusing)? – Pshemo Dec 13 '18 at 17:37
  • Not really enough information here to answer your question. What does each class look like? What kind of changes are you making to `ObjectA`? – Dawood ibn Kareem Dec 13 '18 at 17:37

2 Answers2

4

Java is pass-by-value, which means that if you pass in an instance of ObjectA into an object and later change some state about that object, it will be reflected wherever it was passed in, chiefly because the value of a reference is its location in memory.

How do you fix it? Copy the value into your object so that you don't run the risk of it changing on you. This can be done quickly by newing up an instance of ObjectA when assigning the value.

public void setval(ObjectA val) {
    this.val = new ObjectA(val.getField1(), val.getField2());
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
0

If the value you get from a.getValA() is an Object, it's passed by reference instead of by value. Meaning it's not a copy of the original, but the same object. When you modify it in A, you are also modifying it in B since it's just two references to the same object.

If you share a bit more of detail about how that Object is built, I can edit this to be more specific.

dquijada
  • 1,697
  • 3
  • 14
  • 19