Chapter 2 was the essence of object creation and disappearance. Chapter 3 is about the "Object" class.
-Object is designed mainly to be extended even though it is a concrete class. · All non-final methods (equals, hashCode, toString, clone, finalize) are designed to be overridden, so they have an explicit general contract. -Overriding classes will not work properly unless they comply with the general contract
Overriding the equals method is easy, but it's often the wrong way to override it, so it's best not to override it if any of the following conditions are true:
· When individual instances of a class are inherently unique
· If you are not interested in whether the class provides a "logical equality" check
· If the superclass has already overridden equals and the superclass's behavior is appropriate for this class
· If the class is private or package private and you are certain that its equals method will never be called
Below is the general contract for the equals method. If you do not follow this, the program will behave irregularly or crash.
The implementation of the equals method implements an equivalence relation. That is, Reflexive: x.equals (x) must return true for any non-null reference value x · Symmetric: x.equals (y) must return true only if y.equals (x) returns true for any non-null reference values x and y. Transitive: For any non-null reference value x, y, z, if x.equals (y) and y.equals (z) return true, then x.equals (z) Must return true · Consistent: For any non-null reference values x and y, multiple calls to x.equals (y) are consistent throughout, unless the information used to compare equals to the object is changed. Must either return true or consistently return false
[Read Effective Java] Chapter 3 Item 9 "When overriding equals, always override hashCode" https://qiita.com/Natsukii/items/ac195b5542ba3348ed29
Recommended Posts