[英]Update a String value in hashmap
我有一个哈希图,每次我从其他哈希图中选择一行项目时,该哈希图都会获取数据。 而且我在将数据存储到哈希图中之前在arraylist中进行了检查。 此检查是为了检查itemID在arraylist中是否存在。 如果是,我想更改arraylist中存在的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);
}
问题是,如果找到该密钥,则您正在更新创建的新地图,该地图未存储在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);
}
System.out.println("start");
HashMap<String,String> a1 = new HashMap<String, String>();
a1.put("a1", "true");
a1.put("a1", "true2");
System.out.println("final value is ==" + a1.get("a1"));
我做到了,我得到true2
所以在HashMap
没有替换或覆盖值的概率,只是做一些断点并检查我认为错误是其他地方可能是您想要输入的值也不正确可能是null检查一旦。
可能是如果(exists.equals(itemID))始终为false,只需调试一次
只是这样替换值
int position;
map.get(position).put("String");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.