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

Long runtime/crash when using int[] as key in hashmap

I am following this lesson on dynamic programming: https://youtu.be/oBt53YbR9Kk?t=2330
I found that for some reason if I use a HashMap key with int[], using a large m and n value will take a very long time or crash. If I use a key that is a String instead, it works as expected.

Working Code

    public static void main(String[] args) {
        HashMap<String, Long> map = new HashMap<>();
        System.out.println(gridTraveler(18, 18, map));
    }

    /**
     * Grid Traveler problem
     * */
    public static Long gridTraveler(int m, int n, HashMap<String, Long> memo){
        String key = m + "," + n;
        if(memo.containsKey(key)){
            return memo.get(key);
        }
        if(m == 1 && n == 1) {
            return 1L;
        }
        if(m == 0 || n == 0){
            return 0L;
        }
        memo.put(key, gridTraveler(m - 1, n, memo) + gridTraveler(m, n - 1, memo));
        return memo.get(key);
    }

Broken Code

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

    public static void main(String[] args) {
        HashMap<int[], Long> map = new HashMap<>();
        System.out.println(gridTraveler(18, 18, map));
    }

    /**
     * Grid Traveler problem
     * */
    public static Long gridTraveler(int m, int n, HashMap<int[], Long> memo){
        int[] key = new int[]{m,n};
        if(memo.containsKey(key)){
            return memo.get(key);
        }
        if(m == 1 && n == 1) {
            return 1L;
        }
        if(m == 0 || n == 0){
            return 0L;
        }
        memo.put(key, gridTraveler(m - 1, n, memo) + gridTraveler(m, n - 1, memo));
        return memo.get(key);
    }

Question: Why does an int[] key cause my code to crash compared to just using a String as a key?

>Solution :

Arrays do not override the equals() or hashCode() method from java.lang.Object, but the java.lang.String class does. So, your Map will grow with new objects all the time until it crashes due to memory limits, even though there are already "equal" arrays as keys in the Map. But from the point of view of java, they are not "equal".

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