HashMap 表现异常

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

HashMap behaving weird

问题

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

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

英文:
  1. import java.io.*;
  2. import java.util.*;
  3. class Solution {
  4. public static void main (String[] args) {
  5. HashMap&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();
  6. long sq = 16;
  7. int v = 8, u = 2;
  8. int ans = 0;
  9. map.put(u, map.getOrDefault(u, 0) + 1);
  10. ans += map.getOrDefault(sq/v, 0);
  11. System.out.println(ans);
  12. }
  13. }

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 用作键

改成这样:

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

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

这样也可以工作:

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

The map wants type java.lang.Integer as key

Change to this:

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

Note: Primitive data type int will also work.

This will also work:

  1. 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:

确定