我有一个包含姓名、电话号码和位置的数组列表。
如果可能的话,我想从该数组中删除某些项目
一旦我找到该项目,是否可以像我在下面尝试过的那样将其删除?
public void delete(String nameToDelete)
{
for (Entry entry : Directory.entries) {
if (entry.name.equalsIgnoreCase(nameToDelete))
{
//remove(entry);
}
}
}
谢谢
最佳答案
原因?
ArrayList 返回的迭代器本质上是快速失败
。
The iterators returned by this class's iterator and
listIterator
methods arefail-fas
t: 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 aConcurrentModificationException
. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
当我不使用它时,这个迭代器来自哪里?
对于集合的增强for循环,使用了Iterator
,因此您在迭代时无法调用remove方法。
所以你的循环与下面相同
for (Iterator<Entry> i = c.iterator(); i.hasNext(); ){
那么解决方案是什么?
您可以调用 iterator.remove();
并显式而不是隐式地基于迭代器更改循环。
String inputWord = "john";
ArrayList<String> wordlist = new ArrayList<String>();
wordlist.add("rambo");
wordlist.add("john");
for (ListIterator<String> iterator = wordlist.listIterator(); iterator
.hasNext();) {
String z = iterator.next();
if (z.equals(inputWord)) {
iterator.remove();
}
}
System.out.println(wordlist.size());
现在我可以在哪里阅读更多内容?
关于java - 从数组列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13101279/