1
votes

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
FYI: If you're using a modern java IDE such as Eclipse or NetBeans, you can have your IDE generate equals() and hashCode() methods for you, which takes almost all the effort out of it. The IDEs do a pretty good job of it.Asaph
had already checked this link but it don't ans my question, if i am not using any hashing collection and no one else will ever work on my code why to override hashcode as per contractbanjara
eclipse can do it for me i know quite well but i want to know specific reason about this contract.banjara

3 Answers

2
votes

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.

1
votes

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).

0
votes

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.