0

I know that I should also override hasCode everytime I override equals but what about overloading? Should I still override hashCode?

Side note: before posting the question I've read that I should avoid overloading equals in the first place but I'd still like to know what should I do if I'd choose to overload it.

Claudiu Razlet
  • 350
  • 1
  • 5
  • 12
  • 3
    Overload `equals`? Did you mean *override*? What exactly is your use-case? If you overload it, then it has a very different meaning (i.e. your overload method doesn't override `Object.equals` anymore, see also http://stackoverflow.com/questions/12787947/overriding-object-equals-vs-overloading-it). – Tunaki Jun 11 '16 at 17:56
  • Misread question, sorry, re-opened as that was the wrong duplicate. – Hovercraft Full Of Eels Jun 11 '16 at 18:02
  • @Tunaki i intended indeed overloading equals and i know it defines a new method but still, I didn't knew if I should have override hashCode: I thought that because I was creating a new equals that theoretically I would have always used instead of the one in Object I would have had to also redefine a new hashCode. Your link explained very well why not to overload equals and when overloading could fail (with collections) so thanks +1 – Claudiu Razlet Jun 11 '16 at 18:27

1 Answers1

2

No Hash-based collection will ever use your overloaded equals() method. It's your method, and you decide what it should do. The contract is thus entirely yours.

But I'll repeat what you said in your question: you shouldn't overload equals() in the first place. If you do, you should at least make it consistent with the actual equals(Object) method to avoid most confusions. And since it should be consistent with equals(), that means that you need to override equals(Object), and thus also override hashCode().

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255