Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom function to check whether 2 HashMaps are equal is not working in Java

I’m trying to check whether 2 HashMaps are equal using a custom function match. I expect the output to be true, but the program outputs false. Here is the code snippet.

import java.util.HashMap;

public class HashMapEquals{

    private static boolean matches1(HashMap<Character, Integer> one, HashMap<Character, Integer> two){
        for(char c: one.keySet()){
            if(one.get(c) != two.get(c))
                return false;
        }
        return true;
    }

    private static boolean matches2(HashMap<Character, Integer> one, HashMap<Character, Integer> two){
        for(char c: two.keySet()){
            if(two.get(c) != one.get(c))
                return false;
        }
        return true;
    }

    private static boolean matches(HashMap<Character, Integer> one, HashMap<Character, Integer> two){
        boolean first = matches1(one, two);
        boolean second = matches2(one, two);
        System.out.println(first);
        System.out.println(second);
        return (first && second);
    }

    public static void main(String args[]){
        HashMap<Character, Integer> one = new HashMap<>();
        HashMap<Character, Integer> two = new HashMap<>();

        one.put('a', 10000);
        two.put('a', 10000);

        matches(one, two);
        System.out.println(one.equals(two));
    }
}

The output is

$ java HashMapEquals
  false
  false
  true

I know we can check the same functionality using the inbuilt function of hashmap one.equals(two) which is working as expected. But, I am just curious to know what is wrong with the custom function matches in the above code snippet.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use Objects.equals instead of == or != to compare non-primitives that might be null. Note that you should check that the two Maps have the exact same size instead of doing the value check both ways.

if (!Objects.equals(one.get(c), two.get(c))) return false;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading