• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

hashCode confusion

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please consider the following code:-

class ABC{
public boolean equals(Object o)
{
return true;
}
}
public class HashCodePrint
{
public static void main(String[] args)
{
HashCodePrint ore = new HashCodePrint();
ABC ore1 = new ABC();
System.out.println(ore1.equals(ore));//1
System.out.println(ore.hashCode());//2
System.out.println(ore.hashCode());//3
System.out.println(ore1.hashCode());//4
}
}

In the kathy Sierra & Bert book, under hashCode contract Its written:-
"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.". Now at 1, it shows that the object are equal. But they produce the different integer values at 3 & 4.
Please explain as I think I'm not able to understand this hashCode.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Rohit Men:
... "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." ...


When it says "must," this does not mean it's automatic. It means that the programmer needs to override the hashCode method to ensure that this stays true.

Does that help?
[ September 19, 2005: Message edited by: marc weber ]
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rohit,
You have overridden the equals method, so it is your responsibility to also override the int hashCode( ) method that produces an identical values for the equal objects.
The hashCode values that you are retrieving is the default values generated by the hashCode method of the Object class.
Had you not have overridden the equals method then the output of the equals method would have returned false.

Thanks
Shivakanth.T
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic