My tech blog

Overriding ‘equals’ in Objects

leave a comment »

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’.

Written by alexcuesta

February 5, 2010 at 12:22 pm

Posted in Java

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: