Reputation: 429
I am in some sort of weird problem in Java. I've nailed down the whole problem while debugging it. It happens at these 2 lines:
q=p;
q.addPair(2,3);
notes: p,q is a new class I've defined. In this class, it has a public function addPari(int, int)
.
Here is what I expected: copy p
to q
, then change q
use q.addPair()
, but leave p
the same as before.
I thought this could work, but somehow, it turns out q.addPair(2,3)
will change both p
and q
. Anyone can help me about that?
Upvotes: 0
Views: 96
Reputation: 861
Java assigns by reference, so you would need to do a deep copy in order to copy one object into variable of the same type but then have two seperate objects.
Take a look at this: http://www.jusfortechies.com/java/core-java/deepcopy_and_shallowcopy.php
Upvotes: 0
Reputation: 146
With q=p;
you don't 'copy' p to q, but you instead create a reference for q that points to the instance of p. Now the 2 variables point to the same object.
Upvotes: 0
Reputation: 122366
q=p;
does not actually copy. It means modifying q
will also modify p
as they're the same instance.
If you want q
to be a new object, you need to use new
:
q = new MyObject(p);
In other words, you're using a copy constructor to create a new copy of p
. If your class doesn't have a copy constructor you'll need to create one: it needs to be able to create a new object from an existing one. It can do this by copying over the appropriate values from the given instance p
.
Upvotes: 5