Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4215272

(Mostly) undocumented interaction between hashCode and equals in HashSet

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • 1.4.0
    • 1.2.0, 1.3.0
    • docs
    • beta
    • generic
    • generic



      Name: dbT83986 Date: 02/25/99


      The code below causes two equal() objects to be added
      to a HashSet. Turns out the problem is that I did not
      override hashCode for the class---under Object.hash()
      the two objects are mapped into separate buckets,
      and the equals test is never made.

      This is probably not a bug technically, since the documentation
      for Object.hashCode() does specify that if two objects are
      equals(), then they must produce the same hash value. However,
      this requirement is not mentioned in the documentation for
      equals(), nor in the documentation for HashSet. So the
      documentation doesn't do you any good until you have already
      solved the problem.

      //****************************************************
      import java.util.*;
      import java.io.*;

      public final class Test extends Object {

          private String value;

          public Test (String ss) {
      value = ss;
          }

          public String toString() {
      return value.toString();
          }

          public boolean equals (Object dbv) {
        if (dbv.getClass() != this.getClass())
        return false;
        else { return value.equals(((Test) dbv).value); }
          }

          public static void main(String argv[]) {

      HashSet hs = new HashSet();
      Test s1 = new Test("1");
      Test s2 = new Test("1");

      hs.add(s1);
      hs.add(s2);

      System.out.println(hs);
           }
      }
      (Review ID: 48699)
      ======================================================================

            jhosunw Jamie Ho (Inactive)
            dblairsunw Dave Blair (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: