从标题中可以看出,我试图将HashMap的键与ArrayList中的int进行比较。 对于前47个比较,38 = 38,但在48个比较中,38!= 38.你能帮助我吗?
`@Override
public HashMap<Integer, Integer> populate(int roomId){
ArrayList<Item> original = items.populateTable(roomId);
HashMap<Integer, Integer> refined = new HashMap<>();
for(int i = 1; i < original.size(); i++){
Iterator it = refined.entrySet().iterator();
refined.put(original.get(0).getStockId(), 1); // put the first item in the hashMap
while(it.hasNext()){
Map.Entry pair = (Map.Entry)it.next();
if( pair.getKey().equals( original.get(i).getStockId() ) ) //if item is not in hashMap
{
System.out.println(pair.getKey()+"++");
refined.put(original.get(i).getStockId(), refined.get(original.get(i).getStockId()) + 1); //increment the value
}
else{
System.out.println("NEW:"+pair.getKey());
refined.put(original.get(i).getStockId(), 1); // add it to hashMap
}
}
}
Iterator it1 = refined.entrySet().iterator();
while(it1.hasNext()){
Map.Entry pair1 = (Map.Entry)it1.next();
System.out.println(pair1.getKey() + " = " + pair1.getValue());
}
return refined;
}`
答案 0 :(得分:0)
看起来你正在解决问题来计算数组中遇到的所有数字,如果它是一个案例,你做错了。在迭代中38!= 38(控制台中的'新:38')不再是38,它比较38和39,这就是为什么下一行是'39 ++'。
这可能是你想要做的。
ArrayList<Item> original = items.populateTable(roomId);
HashMap<Integer, Integer> refined = new HashMap<>();
for(int i = 0; i < original.size(); i++){
int key = original.get(i).getStockId();
int count = refined.containsKey(key) ? refined.get(key) : 0;
refined.put(key, count + 1);
}
Iterator it1 = refined.entrySet().iterator();
while(it1.hasNext()){
Map.Entry pair1 = (Map.Entry)it1.next();
System.out.println(pair1.getKey() + " = " + pair1.getValue());
}
输入38,38,38,39,39
可生产
38 = 3
39 = 2