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

(coll) Wanted: A way to customize the equals/hashCode algorithm

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 1.2.2, 1.3.0, 1.4.0, 5.0
    • core-libs

      Name: skT88420 Date: 09/07/99


      The Java 2 SDK includes the classes HashMap, HashSet and Hashtable
      in the java.util package. These classes are all implemented based
      on the usual meaning of Object.equals and Object.hashCode.

      However, suppose I want to create a HashMap (or HashSet, or Hashtable) where
      the usual rules don't apply. For example, I want to create a
      HashMap where two keys are identical if and only if they are the
      exact same object, regardless of the result of Object.equals. To
      accomplish this, I must re-implement nearly all of HashMap just
      to make this one little change. My life would be much simpler if
      there were a couple simple functions which I could override to
      re-define HashMap's concept of a hashCode.

      If HashMap, HashSet and Hashtable used the following methods,
      instead of calling hashCode and equals directly on the key, then
      it would be possible to override them if necessary to customize
      their behavior.


      protected int hashCode(Object o) {
          return (o != null) ? o.hashCode() : 0;
      }

      protected boolean equals(Object a, Object b) {
          return (a == b) || ((a != null) && a.equals(b));
      }


      For example, I could implement the behavior I described earlier
      by simply extending the HashMap class and overriding the above
      methods as...


      protected int hashCode(Object o) {
          return System.identityHashCode(o);
      }

      protected boolean equals(Object a, Object b) {
          return (a == b);
      }
      (Review ID: 94977)
      ======================================================================


      We could create a Hasher interface for the suggested methods.

      public interface Hasher
      {
          public int hashCode(Object hashMe);
          public boolean equals(Object a, Object b);
      }


      These methods are helpful for creating a case-insensitive HashMap.

      ###@###.###

      ======================================================================

            Unassigned Unassigned
            skonchad Sandeep Konchady
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: