The equals-method need to obey the following four rules to remain functional.
Reflexive: x.equals(x) = true
Symmertric: x.equals(y) = y.equals(x)
Transitive: x.equals(y) = y.equals(z) = true -> z.equals(x) = true
Consistent: x.equals(y) remains the same as long as x and y does not change.
How to write a good equals method:
(Regardless of most IDEs autogenerating them)
Given that the hashcode-method is based on the equals-method, it is important to override it after the equals-methods have been overriden.
Otherwise all uses of hashmaps and other hashcode reliant functionalities will become useless.
If the toString-method is not override, it will always write a valueless object-instance reference.
To avoid irrelevant information being printed out (e.g. to logs), it is recommended to override the method and provide relevant object-instance information.
The clone-method is a protected method declared in the original Object.class. However, in order to use it, a class must implement the Cloneable-interface and afterwards override the clone-method.
Within this overridden method, one must call super.clone and return the casted result.
Additionally, two things need to be considered as well:
Since the cloned fields need to be assigned to the clone object, the clone method is not compatible with immutable objects.
The Comparable-interface allows you to implement the compareTo-method, which can be used to declare the rules for how to compare one instance of a class to another instance of the same class.
The compareTo-method returns an int (Integer) value, which can either be a positve, negative or zero, dependent on the result of the comparison.
Having an implementation of the Comparable-interface on DTOs or other types of data containing objects, allows for quick and easy sorting and arrangement of the various instance within lists or arrays.
My name is Daniel H. Jacobsen and I’m a dedicated and highly motivated software developer with a masters engineering degree within the field of ICT.
I have through many years of constantly learning and adapting to new challenges, gained a well-rounded understanding of what it takes to stay up to date with new technologies, tools and utilities.
The purpose of this blog is to share both my learnings and knowledge with other likeminded developers as well as illustrating how these topics can be taught in a different and alternative manner.
If you like the idea of that, I would encourage you to sign up for the newsletter.