Overriding ‘equals’ in Objects
Sometimes it is necessary to override ‘equals’ to assert that the value of one object is equals to another when writing tests in Java because, by default, Java compares instances instead of their values.
There are two ways of implementing this in Java:
- Writing your own implementation:
You can do it yourself or use the IDE’s autogeneration. This is quick but may require maintenance in case the class changes, otherwise equlas will not work.
- Using reflection:
I often use Apache Commons ‘EqualsBuilder.reflectionEquals’. This is slower but does not require maintenance.
Which one to use?
If you are using equals just for testing proposes and you are sure the method is not used on live, I think reflection is the best choice.
If the method is used on live but it does not affect the performance of the application, I think reflection is still a better choice. If performance is important then you will not have any other choice than implementing it yourself.
Also, have in mind that if you override ‘equals’ you also need to override ‘hashcode’.