Hashmap不允许整数作为值

时间:2014-10-09 21:36:27

标签: java hashmap

我的情况要求将Integer添加到Hashmap值,因为我需要根据整数对列表进行排序。我在做如下

Map hmInspStatus = new HashMap();
hmInspStatus.put("Name",Integer.parseInt(strIRName.substring(2,strIRName.length())));

系统抛出一条错误消息,说我无法向HashMap添加整数。我引用了网站中的一些帖子并建议使用HashSet,但是可以将Key,value添加到HashSet吗?

有人可以帮助我实现我想要的目标吗?

由于

2 个答案:

答案 0 :(得分:1)

Modern Java使用generic数据结构。使用给定的泛型类型,Java将处理原始类型的自动装箱。

Map<String, Integer> hmInspStatus = new HashMap<String, Integer>();
hmInspStatus.put("Name",Integer.parseInt(strIRName.substring(2,strIRName.length())));

更新:OP正在使用Java 1.3。此版本不仅不支持泛型,也不支持自动装箱。在这种情况下,您必须跳过泛型并使用手动装箱,或直接从Integer构建String

Map hmInspStatus = new HashMap();
hmInspStatus.put("Name", new Integer(strIRName.substring(2,strIRName.length())));

答案 1 :(得分:0)

执行:

Map hmInspStatus = new HashMap();
hmInspStatus.put("Name",(Integer)Integer.parseInt(strIRName.substring(2,strIRName.length())));
相关问题