Possible Duplicate:
Java: Always override equals?
should I override equals
function for any class that I create?
even for very simple classes which only contains some very simple attributes and by equals I need every single attribute of it to be equal?
We can override the equals method in our class to check whether two objects have same data or not.
If you don't override equals, it will compare the internal address of the two references, which matches the logic behind hashCode.
Case 1: Overriding both equals(Object) and hashCode() method Whenever it(hashcode) is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
Why is it important to override GetHashCode ? It s important to implement both equals and gethashcode, due to collisions, in particular while using dictionaries. if two object returns same hashcode, they are inserted in the dictionary with chaining. While accessing the item equals method is used.
should I override equals function for any class that I create?
Override equals
if (and only if) the object "represents some data", i.e. if it models something such as Person
, Car
or RecipieIngredient
(these typically end up in collections etc). Don't override equals for other types of classes, for example LoginServlet
or DatabaseUtil
.
Remember to always override hashCode
whenever you override equals
.
(A natural follow-up question:) What happens if I don't override equals and hashCode?
Any two objects will be considered unequal unless they are the exact same object.
[...] I need every single attribute of it to be equal?
Typically yes. It depends on how you define your notion of equality. Note that for reference types, you can reuse/delegate to that objects implementation of equals
(and hashCode
) when implementing your own.
Related questions:
You should only override equals()
if you have a reason to do so. As described here, it is very difficult to write a proper equals()
method for non-final or mutable classes.
If your application requires some sort of equality concept that is different from "the identical object", then by all means go ahead. Just read the above reference to be aware of what's involved. But as a matter of routine? Definitely not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With