java.util.ConcurrentModificationException 解决 Android
java.util.ConcurrentModificationException 解决 Android java
在项目里面 遇到了这个bug :
An ConcurrentModificationException is thrown when a Collection is modified and an existing iterator on the Collection is used to modify the Collection as well.
举个通俗的栗子
分析原因:
An iterator over a sequence of objects, such as a collection. If a collection has been changed since the iterator was created, methods next and hasNext() may throw a ConcurrentModificationException. It is not possible to guarantee that this mechanism works in all cases of unsynchronized concurrent modification. It should only be used for debugging purposes. Iterators with this behavior are called fail-fast iterators. Implementing Iterable and returning an Iterator allows your class to be used as a collection with the enhanced for loop.
翻译是
来看看实际解决方案:
1) 在需要迭代的时候 增加一个 锁
2) 每次前迭代 将集合复制一遍
/** * Returns a new array containing all elements contained in this * {@code ArrayList}. * * @return an array of the elements from this {@code ArrayList} */ @Override public Object[] toArray() { int s = size; Object[] result = new Object[s]; System.arraycopy(array, 0, result, 0, s); return result; }
toArray() 方法 会调用 System.arraycopy(array, 0, result, 0, s); 将集合copy一遍
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。