- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
java.util.concurrent.CopyOnWriteArrayList 和 java.lang.Object -6ren">
我知道,类型转换不是正确的词当
java.lang.Object
-> java.util.concurrent.CopyOnWriteArrayList<E>
和
java.lang.Object
-> java.util.AbstractCollection<E>
-> java.util.AbstractList<E>
-> java.util.ArrayList<E>
但我想要的是将 CopyOnWriteArrayList
的行为添加到 ArrayList
。
例如:
我想做以下事情。但是 tstArry 是一个 ArrayList
。不是 CopyOnWriteArrayList
for(TestCls testCls : tstArry)
if(testCls.getVal1().equals("a1"))
tstArry.remove(testCls);
或者这是完成工作的唯一方法?
for(int i = 0; i < tstArry.size(); i++)
if(tstArry.get(i).getVal1().equals("a1"))
tstArry.remove(i--);
tstArry 是我无法控制的类中的 ArrayList。所以,请将 ArrayList 的类型更改为另一种是最可行的解决方案。
最佳答案
你不能remove()
使用增强的 for-each
时来自迭代集合环形。 for-each
循环使用 Iterator<TestCls>
含蓄地。 JavaDoc明确指出
The iterators returned by this class's
iterator()
andlistIterator()
methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's ownremove()
oradd()
methods, the iterator will throw aConcurrentModificationException
.
for-each
loop 在内部创建一个迭代器并使用它来遍历列表。然后你改变列表的结构......并且迭代器必须失败。问题是您无权访问迭代器方法,因此您必须使用 Iterator<TestCls>
明确地。生成的遍历字节码将是相同的,唯一的区别是您可以在遍历列表时从列表中删除元素。
for (Iterator<TestCls> iter = tstArry.iterator(); iter.hasNext(); ) {
TextCls testCls = iter.next();
if(testCls.getVal1().equals("a1")) {
iter.remove();
}
}
澄清 EDIT,因为您显然不熟悉迭代器及其功能。来自 the Oracle tutorial on Collections :
An
Iterator
is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get anIterator
for a collection by calling itsiterator()
method.Note that
Iterator.remove()
is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.Use
Iterator
instead of thefor-each
construct when you need to:
- Remove the current element. The
for-each
construct hides the iterator, so you cannot callremove()
. Therefore, thefor-each
construct is not usable for filtering.
关于java - 有什么办法可以将 "CAST"ArrayList转成CopyOnWriteArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17231022/
我是一名优秀的程序员,十分优秀!