You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中<String,Integer>类型HashMap为何返回null而非String?如何正确取值

问题解答

1. HashMap返回null的原因

你定义Map<String, Integer>时如果传入Integer类型参数调用get方法,就算数值和某个键对应的value一致,也会因为键类型不匹配找不到对应值,返回null。HashMap的get逻辑会先对比键的哈希值,类型不同的对象哈希值大概率不同,就算特殊情况哈希值相同,后续的equals对比也会返回false,最终返回null。

2. <String, Integer>泛型罗马数字转换实现

你原有代码存在两处核心错误:

  • 仅遍历Map的values集合,只能拿到数值,无法直接关联到对应的罗马字符串
  • map.keySet().add(number2)是错误写法:add是向Set集合插入元素的方法,返回值是boolean类型,完全不是你需要的罗马字符串,且键类型为String,传入int参数插入必然失败
    正确实现应该直接遍历Map的键值对集合entrySet,同时拿到罗马字符和对应的数值,修正后的代码如下:
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        int x = 555;
        String result = romanianConverter(x);
        System.out.println(result);
    }

    public static String romanianConverter(int value) {
        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("M", 1000);
        map.put("CM", 900);
        map.put("D", 500);
        map.put("CD", 400);
        map.put("C", 100);
        map.put("XC", 90);
        map.put("L", 50);
        map.put("XL", 40);
        map.put("X", 10);
        map.put("IX", 9);
        map.put("V", 5);
        map.put("IV", 4);
        map.put("I", 1);

        StringBuilder stringBuilder = new StringBuilder("Result = ");
        // 遍历键值对同时获取罗马字符和对应数值
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String romanChar = entry.getKey();
            int num = entry.getValue();
            while (num <= value) {
                stringBuilder.append(romanChar);
                value -= num;
            }
        }
        return stringBuilder.toString();
    }
}

运行上述代码输入555会输出Result = DLV,符合预期。


内容的提问来源于stack exchange,提问作者OverBuffer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:18:02