I have an Object and i just want to override equals method to compare two objects, I am not using any hashing collection anywhere in my program. In such case why there is a contract in hashCode and equals method i.e. If two objects are equal then they should have the same hashcode. shouldn't the general hashcode contract be case specific that if you want to put this object as key in some collection that uses hashing and then overrides it??
3 Answers
I would say yes, as you don't know if you (or more importantly, another developer) will want to put them into a collection using hashing in future. This could be directly, or could be indirectly, i.e. you may pass your object to another method not written by you, and that other method uses a hashed collection in it's implementation.
It's considered good practice (or mandatory) because you can't be sure nobody else (or you next month) will reuse you class.
An object that needs equals is qualified to be used as a key, for example, and so needs hashcode.
You can see that as a convention, like the indentation or the cases of parameters and class names, but that this kind of convention that helps manage the code. Somebody seeing the equals method will rightly assume there is an hashcode method (maybe in a superclass). Don't surprise him (that's a general rule).
That is, you have a lot of helping library to make haschode method and you can get inspiration in the ones of your IDE (Eclipse for example has a function to generate equals and hashcode methods, very verbose but mostly usable after you check and fix them).
If you are redefining equals
, you should redefine hashCode
, but don't need to invest too much effort into it. Simply pick your favorite number (8675309 or whatever) and simply have your hashCode
method return that. Doing so will ensure that hashed collections will behave correctly (albeit slowly) when your object is inserted.
equals()
andhashCode()
methods for you, which takes almost all the effort out of it. The IDEs do a pretty good job of it. – Asaph