Gladwin Rojer
Gladwin Rojer

Reputation: 46

HashMap behaving weird

import java.io.*;
import java.util.*;
class Solution {
    public static void main (String[] args) {
        HashMap<Integer, Integer> map = new HashMap<>();
        long sq = 16;
        int v = 8, u = 2;
        int ans = 0;
        map.put(u, map.getOrDefault(u, 0) + 1);
        ans += map.getOrDefault(sq/v, 0);
        
        System.out.println(ans);
    }
}

The answer should be clearly 1 but it outputs 0. Any idea why it behaves like this? Or Am I missing something?

Upvotes: 1

Views: 56

Answers (2)

DigitShifter
DigitShifter

Reputation: 854

The map wants type java.lang.Integer as key

Change to this:

ans += map.getOrDefault(Integer.valueOf((int) (sq/v)), 0);

Note: Primitive data type int will also work.

This will also work:

ans += map.getOrDefault((int) (sq/v), 0);

Upvotes: 0

Eran
Eran

Reputation: 393801

sq/v divides long by int, so the result is a long, which is boxed to Long when passed to map.getOrDefault(sq/v,0). You have no Long keys in your Map, so it returns the default value 0.

If you change sq to int, the result of sq/v will also be int, and map.getOrDefault(sq/v,0) will return 1.

Upvotes: 1

Related Questions