Re: .equals(o) and Set membership

From: Raymond DeCampo (rdecampo_at_hold-the-spam.twcny.rr.com)
Date: 12/05/03


Date: Fri, 05 Dec 2003 02:37:09 GMT

Murat Tasan wrote:
>
> i thought the Set code checks for membership by applying the .equals()
> method, which at runtime should bind to my overridden method, no?
>

No, that is not correct. Whenever equals() is overloaded, hashCode()
must be overloaded as well. The Collections classes depend on
hashCode() and equals(). Read the javadoc for java.lang.Object
carefully and implement hashCode() for your classes for which you have
overridden equals() and you will see better results.

HTH,
Ray



Relevant Pages

  • Re: Distinct ID Number Per Object?
    ... globally unique as the usual ... hashCode() on the object. ... if equals()) and you'd assign a new higher integer to each one. ... distinct objects that compare equal to have the same ID.) ...
    (comp.lang.java.programmer)
  • Re: Distinct ID Number Per Object?
    ... globally unique as the usual ... hashCode() on the object. ... if equals()) and you'd assign a new higher integer to each one. ... distinct objects that compare equal to have the same ID.) ...
    (comp.lang.java.programmer)
  • Re: equals and hashCode
    ... > I understand the purpose of overriding equals() in comparing the data of ... > an object verses the reference, but the requirement to override hashCode() ... > however unequal objects need not produce distinct hash codes." ... public int hashCode() { ...
    (comp.lang.java.programmer)
  • Re: Java HashSet Problem
    ... overwrite the hashCode() method. ... you need to ignore a critical piece of documentation. ... From the documentation for equals: "Note that it is generally necessary ... overriding equals without maintaining the hashCode contract incorrect. ...
    (comp.lang.java.programmer)
  • Re: HashSet is strange
    ... >>The real answer is that equals and hashCode are closely tied. ... > remove redundancy, so I wont be needing HashSet anymore. ... If your lists will always be ...
    (comp.lang.java.programmer)