This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have not able to clearly decipher the bold lines below
Whenever it (hascode() ) is invoked on the same object more than once during an execution of a java application, the hascode() method must consistently return the same integer, provided no information used in equals() comparison on the object is modified.
Consider a car. Lets say it has a name and type. The equals and hashCode can be based on the name and type. If the name changes the output of equals may change and thus the output of hashCode may also change.
That means, the hashCode() and equals() methods should return same values of their own in every invoking of them on a object, such there is no modification in the object's state, which used to determine the hashCode() and equlas() method.
Simply, without changing the object's fields, which are deterministic functions of the hashCode() and equlas() method, these two method should return the same value!
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Abimaran Kugathasan wrote:That means, the hashCode() and equals() methods should return same values in every invoking of them on a object
hashCode returns int ;where equals return type is boolean
I don't mean in that way, rather, I do mean that they should return same value individually. For example, if equals() method return true, the for every invocation of that method, with the no modification on the object state, should return true, and it also apply to hashCode() which returns a int value.
Sorry for that ambiguity. I just correct that post! Thanks Raman
See the default implementation of equals()(of Object Class) and Hashcode() (of Object Class) is different to implementation in (say,String ) where they are overridden and implemented in such a way that , equals() consider the character sequence as a benchmark to check equality and in same way HashCode() is implemented which make this Line not get contradicted.
If the two objects are equal, the Hashcode() will return the same integer value for both.
So if you override equals in your class you must need to override hashCode() to stick to above line.
Otherwise HashCode() will work abnormal.
Thanks and Regards,
A small leak can sink a Gigantic ship.>
Joined: Sep 12, 2009
When you change any variable , then object is also not same. The object would be different ....as you have said that equals depends on that instance variable two, and two different objects may have different hashcode values.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com