3
ClassName ref = new ClassName();
ref.setCredentials(Credentials);
ref.setVal(value);
ref.setUser(user);

Now when I create a new object of the same class reference, I still get the previous values I have set. Why is this so?

ClassName ref2 = new ClassName();
ref2.setVal(value);
ref2.setUser(user);
ref2.setSomethingNew(somethingNew);

My ref and ref2 instances have all the values [Credentials, Value, User and SomethingNew]. I want to differentiate these two instances. Is it because it's holding the same object?

Update My Lapse:

It's actually ref2 and not ref. I get the values in ref2 which i am not setting, and ref too holds a value which I am setting in the instance of ref2. Both are in same context.

4
  • 1
    you did ref.setVal(...) instead of ref2.setVal(...). Commented Nov 2, 2012 at 9:59
  • ref.equals(ref2) ... what does it result? Commented Nov 2, 2012 at 10:00
  • I don't know why you use same value in both objects. The only way to detect objects are not equal is check based on Reference equality i.e. Check ref2==ref Commented Nov 2, 2012 at 10:14
  • @AmitD ref2==ref is what Object.equals is using that I already suggested. Commented Nov 2, 2012 at 10:17

2 Answers 2

6

Note that with ref2 you are only creating the object, but you are setting the values to ref. You need:

ClassName ref2 = new ClassName();
ref2.setVal(value);
ref2.setUser(user);
ref2.setSomethingNew(somethingNew);

Note the ref2 change instead of ref.

If your ClassName is overriding the equals method, and all the inner objects are equal also, it is normal to have equality between ref and ref2. You can use Object.equals implementation to detect if the objects are different (note different vs. equal).

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

3 Comments

@AmitD Can you provide more details? Maybe I'm missing something.
@dan Edit was not detected by SO it took a while I guess to detect the edit.
@AmitD Yes, it happened to me also, with OP's update. Something is slow today.
3

If you set on ref even after creating ref2 this is what you should expect. Do this:

ref2.setVal(value);

Note: Don't do this:

ref.setCredentials(Credentials);

It sets the class Credentials on ref.

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.