Possible Duplicate:
Overriding equals and hashCode in Java
If I have
class A {
int x = 1;
}
...
A a1 = new A();
A a2 = new A();
a1.equals(a2);
If I compare 2 instances of A without override the equals method, will I get expected result?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That depends on what you expect 🙂
The default implementation will give you reference equality – in other words, when you compare two references,
equalswill only return true if they’re references to the same object.You would normally override
equalsto implement “value equality” – where two distinct objects are deemed equal, usually by virtue of having equal field values themselves. The exact meaning of equality will depend on your design – the two objects could still be distinguishable in other ways, for example.If you override
equals, you should also overridehashCodeto be consistent withequals, such that ifa.equals(b)is true, thena.hashCode() == b.hashCode(). This will allow instances of your class to be used as keys in hash-based collections (e.g.HashMap) so that you can look up a value based on a key which is equal to the original one, rather than having to use a reference to the exact original key object.