0

Let's say I have two objects, A and B where..

Object A=new Object();
Object B=A;

These objects by default each have two ints: int X and int Y. First, in both A and B,

(X == 0) && (Y == 0)

So, you would say those two are equal, as would Java. Now, let's say we change A.X so that A.X=2. Now, A and B are no longer equal since

A.X==2

..but..

B.X==0

Java, however, still says they are equal.

(A.equals(B)) == true
(B.equals(A)) == true

So, how do you get around that?

Steven
  • 1,709
  • 3
  • 17
  • 27

4 Answers4

3

By doing this Object B=A;, you are not creating a new object, but B is pointing to A only. So its only one object.

So when you change A.X = 2, B.X is also 2 at its referring the same variable and hence equal.

You may verify this by printing B.X value.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • Ahh, okay. So is there anyway I can create an exact replica of the object as a new object without having to make a new constructor for it? – Steven Nov 15 '12 at 01:59
  • @StevenFontaine Create a **copy constructor**(to copy values from argument to self) in your class then use the same by passing `A` as arument to create object B as: `Object B = new Object(A);`. If you need help, please let me know. – Yogendra Singh Nov 15 '12 at 02:02
  • Just one question.. What would go in the body of the constructor? Just several lines copying every variable from `A` to `B`? – Steven Nov 15 '12 at 02:07
1

I think everyone (except Mr Singh) is missing a point here:

Object A=new Object(); // Implication is that this is really a user-defined class
Object B=A;

You only have one object here. If you make a change to object A the same change will appear in object B, since they are the exact same object.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
0

You need to override the .equals method of your class that contains the variables. Take a look at this question: How to override equals method in java

Community
  • 1
  • 1
Aaron
  • 23,450
  • 10
  • 49
  • 48
0

If Object is really your own class and not java.lang.Object (if it were then it would have those variables x and y) then it's really a bad class name choice.

Your class must override the .equals method as:

@Override
public boolean equals(Object obj) {
    if(this == obj) return true;
    if(!(obj instanceof MyObject)) return false;
    MyObject other = (MyObject) obj;
    return other.x == this.x && other.y == this.y;
}
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142