HashMap 表现异常

huangapple go评论59阅读模式
英文:

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);
    }
}

答案应该明显是1,但输出却是0。
有任何想法为什么会这样?或者我漏掉了什么?

英文:
import java.io.*;
import java.util.*;
class Solution {
	public static void main (String[] args) {
		HashMap&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();
		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?

答案1

得分: 1

sq/vlong除以int,因此结果是一个long,当传递给map.getOrDefault(sq/v,0)时,它会被装箱为Long。在你的Map中没有Long键,因此它返回默认值0

如果你将sq更改为intsq/v的结果也将是int,并且map.getOrDefault(sq/v,0)将返回1

英文:

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.

答案2

得分: 0

地图需要将类型 java.lang.Integer 用作键

改成这样:

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

注意: 原始数据类型 int 也可以工作。

这样也可以工作:

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

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);

huangapple
  • 本文由 发表于 2020年9月6日 14:43:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63761470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定