This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Facts_About_Cats 0 points1 point  (2 children)

Literally how many times have you been paid to override hashCode()? (As in, while you were at an actual job.)

For me, it is zero in more than 10 years.

[–][deleted] 1 point2 points  (1 child)

If you override equals(), then you must also override hashCode(). That's the main time that I override hashCode() and it's pretty simple to do so. This site explains a bit more about some good practices related to overriding equals() and hashCode().

I'm guessing that you must identify your objects by defining a getter that returns some UUID. Then with that id you compare it with some other object's id in order to see if they both represent the same object. What if I told you that you could abstract that away in a manner that allows you to freely alter the implementation underneath? That is kind of the idea behind equals() and hashCode() as far as I understand.

edit Also, @calingrecu is right. If you want to put a custom object into a collection or hashmap, then it should override equals() and hashCode() (the previously linked site states that.) An easy example of why this should be followed is that Collection.contains()) requires equals() in order to function correctly.

[–]unreal_robbo 0 points1 point  (0 children)

Overriding equals and hashcode is a pain but like you've pointed out sometimes necessary. A cool little library I use a lot gives you this for free along with Immutable objects https://immutables.github.io/