假设我有以下侦听器
interface MyListener {
fun onResult(result: Int)
}
,我的班级列出了此听众的列表
val MyListenerList = ArrayList<MyListener>()
我的疑问是:如果注册听众的人想在回调(onResult
)射击时将其取消(将其从列表中删除),那么最优雅的方法是什么,请注意将其直接称为称为在列表迭代运行时,会导致ConcurrentModificationException
?
不要在 MyListenerList
上迭代,制作 MyListenerList
的副本并在副本上迭代。这样,可以在MyListenerList
上删除而不会引起ConcurrentModificationException
。
例如:
ArrayList(MyListenerList).forEach { it.onRemove(n) }
或
MyListenerList.toArray().forEach { it.onRemove(n) }