-1

Why we should always override hashCode() method whenever we override equals() method? As per my understanding they both seem to fulfill different purpose. hashCode() method is used in hashtables to determine the equality of keys. However equals() method is used to determine the equality of two objects.

Chaitanya
  • 336
  • 2
  • 5
  • 13
  • Both your statements are somewhat wrong. This question has been asked hundreds of times before; you will get more information using google. – Boris the Spider Jan 02 '14 at 12:57
  • Just because 2 values hash to the same value doesn't mean they're equal, you need to check whether they're equal as well. – Bernhard Barker Jan 02 '14 at 12:59
  • You don't need to override both, but it's actually quite easy to do since modern IDEs support code generation for both of them. – Andrey Chaschev Jan 02 '14 at 13:00

1 Answers1

1

If two objects are equal according to the equals method, their hashcodes must be equal as well. Otherwise, lookup in the hash table would fail.

Henry
  • 42,982
  • 7
  • 68
  • 84