Java Tutorial: Testing Equality Of Two Hashmaps

Xah Lee, 2005-02-11

Last time we wrote a function combo() that computes all possible pairs of numbers from a range of numbers 1 to n. See http://xahlee.org/java-a-day/combinatorics.html

However, there's a more efficient algorithm. So we implemented that as the combo2 function below.

Now, the functions combo() and combo2() each returns a HashMap. We want to compute if they are equal, to assure us that combo2 is dandy. So, in this example, we write a code that tests if two HashMap are equal.


import java.util.*;

public class comb {
    static HashMap combo (int n) {
        HashMap result = new HashMap(100);

        for (int j=1; j < n; j++) {
            for (int i=1; i <= n; i++) {
                int m = ((i+j)-1) % n +1;
                if (i < m){ 
                    int[] v= {i,m};
                    result.put(i+ ","+ m, v);
                }
            }
        }
        return result;
    }

    static HashMap combo2 (int n) {
        HashMap result = new HashMap(100);

        for (int j=1; j <= n; j++) {
            for (int i=1; i < j; i++) {
                int[] v= {i,j};
                result.put(i+ ","+ j, v);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        HashMap result = new HashMap(100);
        HashMap result2 = new HashMap(100);
        result = combo(5);
        result2 = combo2(5);
        if (result.keySet().equals(result2.keySet() )) {
            System.out.println("keySet equal: yea");
        } else{
            System.out.println("keySet equal: na");
        }

        if (result.equals(result2 )) {
            System.out.println("HashMap equal: yea");
        } else{
            System.out.println("HashMap equal: na");
        }

        System.out.println(result.toString());
        System.out.println(result2.toString());
    }
}

The interesting line is

if (result.keySet().equals(result2.keySet() )) {

In our case, the keys are strings of the from "i,j", and their values are arrays of int {i,j}.

the keySet() method returns all the keys of the HashMap.

In Java, to compare a HashMap to another, one can use the method equals(). However, if we say:

if (result.equals(result2)) {

that won't work, because apparantly Java's arrays cannot be tested for equality without writing a customized code.

in another day, we'll have to investigate how to test the equality of two HashMaps whose values are arrays...


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet