java.util.concurrent.CopyOnWriteArrayList 和 java.lang.Object -6ren">
gpt4 book ai didi

java - 有什么办法可以将 "CAST"ArrayList转成CopyOnWriteArrayList

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:47:47 25 4
gpt4 key购买 nike

我知道,类型转换不是正确的词当

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() and listIterator() 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 own remove() or add() methods, the iterator will throw a ConcurrentModificationException.

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 an Iterator for a collection by calling its iterator() 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 the for-each construct when you need to:

  • Remove the current element. The for-each construct hides the iterator, so you cannot call remove(). Therefore, the for-each construct is not usable for filtering.

关于java - 有什么办法可以将 "CAST"ArrayList转成CopyOnWriteArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17231022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com