代码
1.快速失败原则是Java检测操作集合操作的一种手段
2.iterator遍历的同时应该不要直接对原有集合操作,而是还要通过iterator
package com.my.livedata.comod
import android.os.Build
import androidx.annotation.RequiresApi
// mutableListOf相当于ArrayList
val observers = mutableListOf<String>()
fun addObserver(observer: String) {
observers.add(observer)
}
@RequiresApi(Build.VERSION_CODES.N)
fun removeObserver(observer: String) {
observers.removeIf {
if (it != null) it == observer else true
}
}
// 替代 removeIf
fun removeObserver2(observer: String) {
val iterator = observers.iterator();
while (iterator.hasNext()){
val next = iterator.next();
if (next == null || next == observer) {
// observers.remove(next) //错误,将导致ConcurrentModificationException
iterator.remove() //正确
}
}
}
@RequiresApi(Build.VERSION_CODES.N)
fun main() {
addObserver("123")
removeObserver2("123")
print(observers)
}
参考:
1.单线程情况下集合出现并发修改异常(ConcurrentModificationException)