When writing one's own classes, is it always necessary to override equals(Object o)
?
If I don't, will it automatically check that all the fields are the same? Or does it just check if the two variables point to the same object?
When writing one's own classes, is it always necessary to override equals(Object o)
?
If I don't, will it automatically check that all the fields are the same? Or does it just check if the two variables point to the same object?
While you shouldn't rely on an IDE, Eclipse provides this canned functionality by pressing alt + shift + s and selecting the equals and hashCode menu options. There is also a toString option. Effective Java by Josh Bloch has good info on this subject. The link will take you to the chapter hosted on Google Books that discusses this topic.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.You should always override the equals() method if the identity operator is not appropriate for your class.
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
If one is writing a class that is going to have its objects be compared in some way, then one should override the
equals
andhashCode
methods.Not providing an explicit
equals
method will result in inheriting the behavior of theequals
method from the superclass, and in the case of the superclass being theObject
class, then it will be the behavior setforth in the Java API Specification for theObject
class.The general contract for providing an
equals
method can be found in the documentation for theObject
class, specifically, the documentation of theequals
andhashCode
methods.Only override
equals()
if it makes sense. But obviously if you overrideequals()
you need to ensure that thehashcode()
contract isn't broken, meaning if two objects are equal they must have the same hash code.When does it make sense? When
Object.equals()
is insufficient. That method basically comes down to reference identity, meaning two objects are the same object so:Numbers are an obvious example when it makes sense because
Integer(10)
should equal anotherIntger(10)
.Another example could be when you're representing database records. Let's say you have Student records with a unique integer ID, then it might be sufficient implementation of equals to simply compare the ID fields.