Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should all classes have a .equals and .hashcode method?

I'm working on a unit testing project where the asserts call the .equals method. However the people on the project before didn't generate these methods.

Is it considered best practice to auto generate these methods as you code? Should all coders be doing this?

I was searching for more information on the .equals and .hashcode method and most of them seem to be geared towards how to implement or override them.

like image 436
Ej_840 Avatar asked Oct 28 '25 08:10

Ej_840


1 Answers

It's mostly a question of taste - if you don't expect to use the equals method (e.g., aren't using assertEquals, never mean to use this class as a key in a Map, etc), writing it means you may be writing dead code, and some conventions would advocate avoiding it.

Here, there doesn't seem to be a question - if you intend to use assertEquals, you need an the equals method implemented. If you're going to implement it, you should probably also implement hashCode in order to future proof your code against sneaky, hard to find, bugs.

like image 173
Mureinik Avatar answered Oct 30 '25 23:10

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!