0

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?

1
  • Java never copies anything. Commented Nov 27, 2013 at 18:10

3 Answers 3

5
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just a note on this; Java doesn't supply copy constructors by default so you'll have to implement it yourself in the class of which P and Q are instances.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.