9 Replies Latest reply: Feb 10, 2011 5:03 AM by EJP RSS

    HashMap.hashCode() for HashMap with keys equaling their values

    800343
      Hi

      I've found something strange with Hashmaps:

      in the following code:

      HashMap<Integer,Integer> m1 = new HashMap<Integer,Integer>();
      HashMap<Integer,Integer> m2 = new HashMap<Integer,Integer>();
      m1.put(1,1);
      m1.put(2,2);
           
      m2.put(2,2);
      m2.put(1,1);
      m2.put(5,5);
           
      System.out.println(m1.equals(m2));
      System.out.println(m1.hashCode());
      System.out.println(m2.hashCode());


      The output received is:
      0
      0
      false

      It seems that when a HashMap receives key/value pairs where key = value its hashCode becomes 0!
      I'm pretty sure I haven't just stumbled on a bug in the Collections framework so could someone please explain to me why this occurs?

      ps: If your wondering why on earth someone would want to make such a Hashmap, I've found it useful in the following situation:

      class MyCount {
           int count;
           String name;
           int age;

           MyCount(String name, int age) {
           this.name = name;
           this.age = age;
           count = 0;
           }

           void add(int c) {
           count += c;
           }

           public int hashCode() {
           return 31 * age + name.hashCode();
           }
      }

      class MyCountClusterer {
           Collection<MyCount> cluster(MyCount[] counts) {
           HashMap<MyCount, MyCount> countMap = new HashMap<MyCount, MyCount>();
           for (MyCount c : counts) {
                MyCount mapC = countMap.get(c);
                if (mapC == null) {
                mapC = new MyCount(c.name, c.age);
                countMap.put(c, c);
                }
                mapC.add(c.count);
           }
           return countMap.values();
           }
      }