I was make some code and found that objects ar eno equals - it is trivial question but not understand how default equals works.
class A {
String id;
public A(String id) {
this.id = id;
}
public static void main(String args[])
{
A a = new A("1");
A b = new A("1");
System.out.println(a.id);
System.out.println(b.id);
System.out.println(a.equals(b));
}
}
Result is:
1
1
false
But I want to have a.equals(b) == true
why it is false
?
If you don't override equals() on the object, you are comparing two different memory references. So override equals() to compare the id fields.
Your class currently extends only
Object
class and in Object classequals
method looks like thisWhat you need is to override this method, for example like this
Also when you override
equals
you probably should overridehashCode
method, but this is not subject of your question. You can read more about it here.you should rewrite an equals() method for your code, as you would a toString() method.
It overrides
Object
'sequals
method by default, it checks the "same object" rather than "same content". If you want to havea.equals(b) == true
, you should override it:----- EDITED -----