-1

Should the equals (Object) method be overridden when overriding hashCode() in Java?

I have read the contract that overriding equals, you should override hashCode. Is the vice versa true?

I was thinking of a scenario where I don't compare objects, no equals method.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
abhi
  • 611
  • 1
  • 6
  • 17
  • 1
    Simple answer: yes. Detailed answer: check the possible dup. – Luiggi Mendoza May 09 '13 at 17:11
  • It is not the Duplicate , asked with a special intent – abhi May 09 '13 at 17:16
  • If you understand the concept, then you will know the answer. Since you don't understand it, you must read the concept again. By the way, from the dup Q/A: *If you override one, then you should override the other.* There you have your answer. – Luiggi Mendoza May 09 '13 at 17:17
  • Well Luiggi , i think i understand the concept and to further clear that i was seeking an answer.The thing that was running through my mind was if i dont use hashmap or set maybe , or any other scenario where equals will not be called . I understand it is a contract and it is recomended .Thnaks for the answers – abhi May 13 '13 at 05:12

2 Answers2

5

Yes, it should be overridden. If you think you need to override hashCode(), then you need to override equals() and vice versa. The general contract of hashCode() is:

  1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  3. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

NINCOMPOOP
  • 46,742
  • 15
  • 123
  • 158
1

Joshua Bloch makes it clear in chapter 3 of his "Effective Java" - these must be in lockstep. They should always be overridden together.

duffymo
  • 293,097
  • 41
  • 348
  • 541