所以我尝试通过指定来使用 HashMap:
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;
}
最佳答案
改变
HashMap totalAtt = new HashMap<String, Integer>();
至
HashMap<String, Integer> totalAtt = new HashMap<>();
和
HashMap sAtt
至
HashMap<String, Integer> sAtt
关于java - 在 HashMap 中使用整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658300/