Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we always override equals?

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?

like image 370
Nick Heiner Avatar asked Oct 11 '09 01:10

Nick Heiner


1 Answers

If one is writing a class that is going to have its objects be compared in some way, then one should override the equals and hashCode methods.

Not providing an explicit equals method will result in inheriting the behavior of the equals method from the superclass, and in the case of the superclass being the Object class, then it will be the behavior setforth in the Java API Specification for the Object class.

The general contract for providing an equals method can be found in the documentation for the Object class, specifically, the documentation of the equals and hashCode methods.

like image 173
coobird Avatar answered Oct 12 '22 22:10

coobird