我试图从 arraylist 中删除该项目但抛出 concurrentmodificationexception
listIterator = CustomListArr.iterator();
for (ClassA value : CustomListArr) {
try {
String query = "SELECT * FROM DEVICE_INFO WHERE DEV_IP='" + value.getaddress() + "'";
String address = value.getiip();
SQLiteDatabase db = dbController.getReadableDatabase();
Cursor cursor1 = db.rawQuery(query, null);
if (cursor1 != null) {
if (cursor1.moveToFirst()) {
do {
while (listIterator.hasNext()) {
String ss = listIterator.next().getiip();
if (ss.equals(ippaddress)) {
listIterator.remove();
} else {
System.out.println(ss);
}
}
CustomHotspotListArr.size();
} while (cursor1.moveToNext());
}
}
} catch (Exception e) {
String error = e.toString();
}
}
if (CustomListArr.size() > 1) {
list_adapter_configure = new CustomListview(Conf_devicelist.this, R.layout.conf_items, CustomListArr);
lv_configrue.setAdapter(list_adapter_configure);
} else if (CustomListArr.size() == 1) {
startActivity(new Intent(getApplicationContext(), New_Activity.class));
finish();
} else if (CustomListArr.size() == 0){
Toast.makeText(Conf_devicelist.this, "No New Device Found", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
最佳答案
显然这段代码创建了一个迭代器(我们称之为 A):
listIterator = CustomListArr.iterator();
但不是很明显,这段代码还创建了一个迭代器(我们称它为 B):
for (ClassA value : CustomListArr) {
因此,当您使用迭代器 B 遍历 CustomListArr
时,您读取了数据库,然后开始使用迭代器 A 遍历 CustomListArr
。如果您使用A,然后回到迭代器 B 的循环,迭代器 B 注意到列表在其背后被更改并抛出 ConcurrentModificationException
。
我看到对 CustomHotspotListArr
的引用,所以我想知道这些迭代器中的一个是否应该在这个列表中。
这段代码有很多问题。迭代器 A 是在开始时创建的,因此它永远不会遍历列表一次以上。我什至不确定这段代码应该做什么,删除列表中具有特定 IP 地址的所有项目,或者只是删除重复项。
关于android - 如何避免数组列表中的并发修改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38971688/