Results 1 to 2 of 2
  1. #1
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Zurich, Switzerland
    Rep Power

    Default the hashCode() contract

    according to my scjp book (Exam 310-065) there are no hashCode requirements when x.equals(y) otherwise I would have a problem for a class Person that has a field name as String. Instantiating two Persons with new Person("May") and new Person("Amy") equals() returns true, but for me equals() should return false, since May and Amy are not the same. I override equals() so that each char is compared with the other char and if one comparison fails equals() returns false. So far all ok. but suppose you sould generate also a different hashCode for the two Strings May and Amy, how?

    All other conditions and requirements for a valid hashCode() contract are clear!
    Last edited by j2me64; 09-04-2011 at 10:59 AM.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Madgaon, Goa, India
    Rep Power

    Default Re: the hashCode() contract

    There's absolutely no requirement that different instances of the same class, for which equals(...) returns flase, must have differing hashCode. In fact, it's usually impossible, as the number of different, non-equal instances is usually more than Integer.MAX_VALUE.

    A well distributed hashCode can however improve the performance of a hash based collection (Hashtable, HashMap etc). If you're never going to use instances of the class in a hash based collection, you might as well have hashCode() return 0 (or 1, or any constant).

    For more, search the net for "hashcode collision"


Similar Threads

  1. hashCode idea
    By Markgm in forum New To Java
    Replies: 20
    Last Post: 08-14-2011, 03:37 PM
  2. equals() and HashCode()
    By jomypgeorge in forum New To Java
    Replies: 1
    Last Post: 02-10-2011, 07:34 AM
  3. hashCode() contract
    By jomypgeorge in forum New To Java
    Replies: 3
    Last Post: 01-14-2011, 11:32 AM
  4. hashCode questions
    By alpdog14 in forum New To Java
    Replies: 3
    Last Post: 02-19-2010, 11:00 PM
  5. An acceptable hashcode?
    By in forum New To Java
    Replies: 7
    Last Post: 03-29-2009, 09:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts