我有一个 HashMap ,每次我从其他 HashMap 中选择一行项目时,它都会获取数据。在将数据存储到 HashMap 中之前,我已经检查了数组列表。这个检查是检查arraylist中是否存在itemID。如果是,我想更改数组列表中存在的 itemID 的数量值。目前的问题是数量从未更新或改变。
我知道这不是最好的方法,但是有人可以帮助我解决这个问题吗?提前致谢。
这是我目前的代码
private void listOrder(String itemValue, String itemID)
{
HashMap<String, String> map = new HashMap<String, String>();
String quantity = "1";
map.put(FOODID3, itemID);
map.put(FOODNAME3, itemValue);
map.put(FOODQUANTITY3, quantity);
boolean found = false;
if (!LIST3.isEmpty())
{
for (int i = 0; i < LIST3.size(); i++)
{
String exists = null;
exists = LIST3.get(i).get(FOODID3).toString();
if (exists.equals(itemID))
{
found=true;
String b = map.get(FOODQUANTITY3);
int quantityy = Integer.parseInt(b) +1;
String c = Integer.toString(quantityy);
System.out.println(c);
map.put(FOODQUANTITY3, c); // I can't update the value here
break;
}
}
}
if (!found)
{
LIST3.add(map);
}
LISTORDER = (ListView) findViewById(R.id.listOrder);
List3Adapter adapter = new List3Adapter(MainActivity.this, LIST3);
LISTORDER.setAdapter(adapter);
}
最佳答案
问题是,如果找到 key ,您正在更新您创建的新 map ,该 map 未存储在 list3 中。
尝试以下代码,它会起作用:
private void listOrder(String itemValue, String itemID)
{
HashMap<String, String> map = new HashMap<String, String>();
String quantity = "1";
map.put(FOODID3, itemID);
map.put(FOODNAME3, itemValue);
map.put(FOODQUANTITY3, quantity);
boolean found = false;
if (!LIST3.isEmpty())
{
for (int i = 0; i < LIST3.size(); i++)
{
String exists = null;
exists = LIST3.get(i).get(FOODID3).toString();
if (exists.equals(itemID))
{
found=true;
String b = LIST3.get(i).get(FOODQUANTITY3);
int quantityy = Integer.parseInt(b) +1;
String c = Integer.toString(quantityy);
System.out.println(c);
LIST3.get(i).put(FOODQUANTITY3, c); // I can't update the value here
break;
}
}
}
if (!found)
{
LIST3.add(map);
}
LISTORDER = (ListView) findViewById(R.id.listOrder);
List3Adapter adapter = new List3Adapter(MainActivity.this, LIST3);
LISTORDER.setAdapter(adapter);
}
关于java - 更新 hashmap 中的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20540164/