hc-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Mike Moran <mike_mo...@mac.com>
Subject HashMap does use equals() [was Re: DO NOT REPLY [Bug 18355] - HttpState cannot differentiate credentials for different hosts with same Realm names]
Date Thu, 03 Apr 2003 12:05:17 GMT
bugzilla@apache.org wrote:
[ ... ]

>The reason is because HashMap only compares the hashCodes of 
>the objects and never consults equals. 
>
[ ... ]

This is not the case. HashMap uses equals() when the hashCode() of two 
objects are the same. If you want good performance it is a good idea to 
have the hashCode() different or at least evenly distributed. However, 
it is not necessary. As a test, try the following code:

import java.util.*;

public class HashMapThing
{
    private static class Key
    {
        private int hashCode;
        private String content;
        private String tag;

        public Key(int hashCode, String content, String tag)
        {
            this.hashCode = hashCode;
            this.content = content;
            this.tag = tag;
        }

        public int hashCode()
        {
            System.out.println("hashCode() called on " + toString());
            return hashCode;
        }

        public boolean equals(Object o)
        {
            System.out.println("equals() called on " + toString()
                               + ", " + o.toString());
            if (o instanceof Key) {
                Key other = (Key) o;
                return this.content.equals(other.content);
            }
            else {
                return false;
            }
        }
       
        public String toString()
        {
            return "tag: \"" + tag
                + "\" code: " + hashCode
                + " content: \"" + content + "\"";
        }
    }

    public static void main(String[] args) throws Exception
    {
        Key entryA = new Key(0, "0", "A");
        Key entryB = new Key(0, "0", "B");
        Key entryC = new Key(0, "1", "C");

        System.out.println("Adding entries:");
        Map map = new HashMap();
        System.out.println("A");
        map.put(entryA, "1");
        System.out.println("B");
        map.put(entryB, "2");
        System.out.println("C");
        map.put(entryC, "3");

        System.out.println("\nGetting entries:");
        String out1 = (String) map.get(entryA);
        String out2 = (String) map.get(entryC);

        System.out.println("\nEntries:");
        System.out.println("1: " + out1);
        System.out.println("2: " + out2);
    }
}

-- 
Mike


Mime
View raw message