-4

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?

Line
  • 1,529
  • 3
  • 18
  • 42
Java Kumara
  • 97
  • 2
  • 12
  • 2
    We can not see what you miss, if you not show what you have. – Jens Nov 11 '14 at 12:09
  • 1
    Why do you ask a question if you post a self-answer in the very same minute? – Philipp Reichart Nov 11 '14 at 12:10
  • I figured out what was the problem. And I got a fix for it. I thought of sharing. If so many negativity is there about that, I am sorry. I should've kept it myself I guess. – Java Kumara Nov 11 '14 at 12:54
  • 1
    @JavaKumara don't misinterpret the comment as hate, it's not about you it's about the question, Stackoverflow is not a forum, it's a Q&A site that. And this sites has guidelines like avoiding duplicate questions, unclear questions, minimum understanding of the problem, etc... All of that to create a site where content is great. There's already multiple questions that have been answered in the past on this topic by the way : http://stackoverflow.com/questions/12147297/how-do-i-assert-equality-on-two-classes-without-an-equals-method – bric3 Nov 12 '14 at 13:04
  • Thanks @Brice. I wasn't aware of the guidelines. Will go through. – Java Kumara Nov 13 '14 at 07:21

2 Answers2

4

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Ekansh Rastogi
  • 2,418
  • 2
  • 14
  • 23
0

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.

Java Kumara
  • 97
  • 2
  • 12