Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Even though I have two data objects of a custom class which are equal w.r.t all the variables, assertEquals() method is failing. What am I missing here?
For comparing two objects you need to override the equals()
method of the Object
class.
When you create two objects of a class, say class A
, then the objects are different even if they have all the same variables. This is because the equals method or ==
both check if the reference of the objects are pointing to the same object.
Object o1 = new A();
Object o2 = new A();
o1.equals(o2);
Here the equals method will return false, even if all the fields are null
or even if you assign same values to both the objects.
Object o1 = new A();
Object o2 = o1;
o1.equals(o2);
Here the equals method will return true, because the object is only one, and both o1
, o2
references are pointing to same object.
What you can do is override the equals
method
public class A {
@Override
public boolean equals(Object obj) {
if (obj==this) return true;
if (obj==null || obj.getClass()!=this.getClass()) return false;
return (this.id==((A) obj).id);
}
// You must also override hashCode() method
}
Here we say objects of class A
are equal if they have same id. You can do same for multiple fields.
Comparison to check if its equals are not happens with the help of the equals() function. You need to override this method in your custom class.
public boolean equals(Object obj) { }
Please also make sure you override hashCode() method as well.