Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

hashCode(), compareTo() and equals()

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Are these methods related by any means?
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Such vague questions are not very helpful. What have you read about the methods that you do not understand?

Read this if you have nothing else.
[ August 27, 2005: Message edited by: Barry Gaunt ]
 
Ranch Hand
Posts: 380
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes.

** Equal objects must have equal hash codes.

And

** If the 2 objects are returning 0 using compareTo() then they must return true using equal() as well given that the objects are mantained in a sorted map. (Where Comparable interface is overrided if needed to be).
 
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See the Discussion for the methods equals() and hashCode() in the java API documentation under the class "Object" that is by far the best guide you can get.
 
shuba karthik
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if equals() return true should compareTo() return 0
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes.
The compareTo() method will return a negative number, zero, or positive number depending on whether the Object is less than, equal to, or greater than the Object argument. It is recommended that Objects that implement the compareTo() should ensure that if the equals() method of the Object return true then the same comparison using compareTo( ) should return zero.
reply
    Bookmark Topic Watch Topic
  • New Topic