如何避免ArrayList中

如何避免ArrayList中

问题描述:

ConcurrentModificationException的我试图从数组列表中删除项目,但抛出ConcurrentModificationException的如何避免ArrayList中

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地址删除列表中的所有项目,或者删除重复项目。

+0

感谢您的回答。在CustomListArr中使用CopyOnWriteArrayList后,异常被清除。 –