谁能告诉我我哪里错了?
File promoCountFile = new File(RaconTours.PATH + "promocodeCount.txt");
if (promoPlistPath.exists()) {
try {
ObjectInputStream inStream = new ObjectInputStream(new FileInputStream(promoPlistPath));
ObjectInputStream promoStream = new ObjectInputStream(new FileInputStream(promoCountFile));
promoobj = (ArrayList<HashMap<String, Object>>) promoStream.readObject();
obj = (ArrayList<HashMap<String, Object>>) inStream.readObject();
for (HashMap<String, Object> tmpObj : obj) {
promoTourname = (String) tmpObj.get("promoTour");
promocodeID = (String) tmpObj.get("promocode");
if (promoTourname.equals(currentTour.getObjtourName())) {
//if the condition is met, remove the entry from the file
for (HashMap<String, Object> promoTemp : promoobj) {
promoTourCount = (Integer) promoTemp.get("promocodeTourCount");
}
obj.remove(tmpObj);
--promoTourCount;
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(promoPlistPath));
out.writeObject(obj);
out.close();
ObjectOutputStream promoout = new ObjectOutputStream(new FileOutputStream(promoCountFile));
HashMap<String, Object> promoCountDict = new HashMap<String, Object>();
promoobj.remove(0);
promoCountDict.put("promocodeTourCount",promoTourCount);
promoobj.add(promoCountDict);
promoout.writeObject(promoobj);
promoout.close();
}
}
if (obj.size() == 0 || promoTourCount == 0) {
promoPlistPath.delete();
promoCountFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
在这里,它给我并发修改异常,而for循环迭代第二次或之后。
我试图在每次循环迭代时更新文件中的promoTourCount值。但我做不到。因为为了避免增加多个对象,我删除了位置0的对象,并在该位置添加了新的对象(promoobj.remove(0);)
请帮帮我
您正在修改要迭代的集合。这将触发一个错误。你在这里迭代obj:
for (HashMap<String, Object> tmpObj : obj) {
但是从这里删除:
obj.remove(tmpObj);
我建议您将要删除的项存储在另一个集合中,只有在完成for循环时才将它们从映射中删除。
编辑: & lt; & lt;添加示例代码>
List<Integer> toRemove = new LinkedList<Integer>();
for (int i = 0; i < obj.size(); i++) {
HashMap<String, Object> tmpObj = obj.get(i);
if (/* something */) {
/* ... */
/* obj.remove(tmpObj); replaced with*/
toRemove.add(0, i); // notice that I add bigger indices first
}
}
// Here we make the removal from bigger indices to smaller ones
// Notice that we iterate and remove from different collections.
for (Integer indexToDelete : toRemove) {
obj.remove(indexToDelete);
}
这是想要删除元素时的基本思路。但是,您需要在for循环中立即输出修改后的obj。那么,对索引进行一些修改可能会更好:
for (int i = 0; i < obj.size(); i++) {
HashMap<String, Object> tmpObj = obj.get(i);
if (/* something */) {
/* ... */
/* obj.remove(tmpObj); replaced with*/
obj.remove(i); // We erase the element but this time we do not use enhanced for loop which is ok.
i--; // we decrease the index because th enumber of elements decreased. Index hack. Ugly.
System.out.println(obj); // modified obj :)
}
}