在HashMaps中使用Integer

时间:2016-04-15 23:17:24

标签: java

所以我试图通过指定:

来使用HashMaps
HashMap totalAtt = new HashMap<String, Integer>();

但是当我尝试添加两个整数时,它会给出一个错误操作数的错误。如何在没有编译器错误或警告的情况下添加从此HashMap检索的整数?

编辑:替换了一些代码,不再出现编译器错误,而是警告未经检查或不安全的操作

public HashMap<String, Integer> getAttrib()
{
    HashMap<String, Integer> totalAtt = new HashMap();

    //Creates key values and initializes them to 0
    totalAtt.put("strength", 0);
    totalAtt.put("dexterity", 0);
    totalAtt.put("constitution", 0);
    totalAtt.put("intelligence", 0);
    totalAtt.put("wisdom", 0);
    totalAtt.put("charisma", 0);

    HashMap<String, Integer> sAtt;

    for(Sprite s: itemList)
    {
        //iterates through items and counts their attributes
        sAtt = s.getAttrib();

        totalAtt.put("strength", totalAtt.get("strength") + sAtt.get("strength"));
        totalAtt.put("dexterity", totalAtt.get("dexterity") + sAtt.get("dexterity"));
        totalAtt.put("constitution", totalAtt.get("constitution") + sAtt.get("constitution"));
        totalAtt.put("intelligence", totalAtt.get("intelligence") + sAtt.get("intelligence"));
        totalAtt.put("wisdom", totalAtt.get("wisdom") + sAtt.get("wisdom"));
        totalAtt.put("charisma", totalAtt.get("charisma") + sAtt.get("charisma"));
    }

    return totalAtt;
}

来自Sprite类:

public HashMap<String, Integer> getAttrib()
{
    return attrib;
}

1 个答案:

答案 0 :(得分:3)

更改

HashMap totalAtt = new HashMap<String, Integer>();

HashMap<String, Integer> totalAtt = new HashMap<>();

HashMap sAtt

HashMap<String, Integer> sAtt