java - 从数组列表中删除对象

标签 java arraylist

我有一个包含姓名、电话号码和位置的数组列表。

如果可能的话,我想从该数组中删除某些项目

一旦我找到该项目,是否可以像我在下面尝试过的那样将其删除?

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 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. 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());

现在我可以在哪里阅读更多内容?

  1. The For-Each Loop
  2. ArrayList Java docs

关于java - 从数组列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13101279/

相关文章:

java - 我的应用程序启动 Play 商店后,它会立即返回到该应用程序

java - 对于该应用程序来说,哪种数据库架构是一个不错的选择?

java - 无法解析符号 Instagram 应用

java - 将元素移动到第一位时,ArrayList 与 LinkedList 的复杂性

c# - 在 ASP.NET 中使用Where子句

java ;一个数组列表的两个本地克隆是否使它们的值相等?

java - 在同一端口使用两个本地 ip

java - hibernate createSQLQuery批量插入

c# - 多个数组计数比较 C#

android - 如何使用 picaso 库而不是可绘制资源将图像作为 url 传递到 arraylist 中?