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

(coll spec) Comparator javadocs error regarding sets and equals()

XMLWordPrintable

      The following text in the javadocs for java.util.Comparator is wrong:

        For example, if one adds two keys a and b such that
            (a.equals((Object)b) && c.compare((Object)a, (Object)b) != 0)
        to a sorted set with comparator c, the second add operation will return false
        (and the size of the sorted set will not increase) because a and b are
        equivalent from the sorted set's perspective.


      In fact, the sorted set's behaviour depends on the Comparator and
      NOT on equals() as the following program illustrates:


      $ cat Main.java
      import java.util.*;

      public class Main {

          static public class Men {
              public int value;
              
              public Men(int v) {
                  value = v;
              }

              public String toString() {
                  return "Men" + value;
              }
       
              /** We hold these truths to be self evident..... */
              public boolean equals(Object o) {
                  return (o instanceof Men);
              }
          }

          public static void main(String[] args) {
              Comparator c = new Comparator() {
                      /* Note: inconsistent with equals() */
                      public int compare(Object o1, Object o2) {
                          return ((Men)o1).value - ((Men)o2).value;
                      }
                  };

              TreeSet set = new TreeSet(c);

              Men m1 = new Men(1);
              Men m2 = new Men(2);

              System.out.println("m1.equals(m2) is " + m1.equals(m2));
              System.out.println("c.compare(m1, m2) is " + c.compare(m1, m2));

              System.out.println("Adding m1 is " + set.add(m1));
              System.out.println("Adding m2 is " + set.add(m2));
              System.out.println("set: " + set + " has size " + set.size());
          }
        
      }

      $ java Main
      m1.equals(m2) is true
      c.compare(m1, m2) is -1
      Adding m1 is true
      Adding m2 is true
      set: [Men1, Men2] has size 2

            sseligmasunw Scott Seligman (Inactive)
            duke J. Duke
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: