这是我的代码,我在其中将数据添加到列表中:
fun bindProcess(listOfDocId: MutableList<String>, isActvityLogEnabled: Boolean): Observable<MutableList<SearchResultModel>> {
return Observable.create<MutableList<SearchResultModel>> {
var filteredList =CopyOnWriteArrayList<SearchResultModel>()// mutableListOf<SearchResultModel>()
val headerItem: SearchResultModel = SearchResultModel()
headerItem.type = 0
headerItem.title = context.getString(R.string.top_matches_label)
filteredList.add(headerItem)
for (row in ContSyncApplication.getContacts()) {
if (listOfDocId.contains(row.docId)) {
val myData: SearchResultModel = SearchResultModel()
myData.type = 1
myData.docId = row.docId
myData.name = row.display_name
if (!row.profile_image.isNullOrBlank()) {
myData.imagePath = row.profile_image!!
}
filteredList.add(myData)
if (isActvityLogEnabled && DatabaseQueryHelper.checkActivityLogById(row.docId)) {
val myactivityData: SearchResultModel = SearchResultModel()
myactivityData.type = 1
myactivityData.docId = row.docId
myactivityData.name = row.display_name
myactivityData.imagePath = row.profile_image ?: ""
mActvityList.add(myactivityData)
}
}
}
if (mActvityList.size > 0) {
val activityHeader: SearchResultModel = SearchResultModel()
activityHeader.type = 0
activityHeader.title = "Activity Log"
filteredList.add(activityHeader)
filteredList.addAll(mActvityList)
}
it.onNext(filteredList)
it.onComplete()
}
}
当我在列表中执行并添加数据时,我得到ConcurrentModificationException
。任何人都可以建议我如何执行循环,以便我可以解决这个问题?我必须搜索并添加到列表中。
答案 0 :(得分:0)
在使用for each
进行遍历时,检查是否要修改相同的集合。如果要修改相同的集合,则需要使用iterator
。
答案 1 :(得分:-2)
val tempList = arrayListOf<MyObject>()
tempList.addAll(currentList)
currentList.forEach {
if (condition to remove here) {
tempList.remove(it)
}
}
currentList = tempList