从数组列表中删除对象 [英] Removing an object from a arraylist

查看:30
本文介绍了从数组列表中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an arraylist with names, phone numbers and locations.

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

I would like to remove certain items from that array if possible

无论如何,一旦我像下面尝试过的那样找到它,就可以删除它吗?

Is there anyway to remove the item once I have found it like I have tried below?

public void delete(String nameToDelete) 
{    
    for (Entry entry : Directory.entries) { 
        if (entry.name.equalsIgnoreCase(nameToDelete))
        {
            //remove(entry);
        }
    }
}

谢谢

推荐答案

原因?

ArrayList 返回的迭代器是 fail-fast 本质上.

Reason?

Iterators returned by ArrayList is fail-fast in nature.

该类的迭代器和listIterator方法返回的迭代器为fail-fast:如果在迭代器创建后的任何时间对列表进行结构修改,在任何除非通过迭代器自己的remove 或add 方法,否则迭代器将抛出一个ConcurrentModificationException.因此,面对并发修改,迭代器会快速而干净地失败,而不是冒着在未来不确定的时间出现任意、非确定性行为的风险.

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 方法.

Where does this iterator Come from while I am not using it?

For enhanced for loop for collections Iterator gets used so you can not call remove method while you are iterating.

所以你的循环和下面一样

So your loop is same as below

for (Iterator<Entry> i = c.iterator(); i.hasNext(); ){   

那么解决方案是什么?

您可以调用 iterator.remove(); 并基于迭代器显式而不是隐式地更改循环.

What is the Solution Then ?

You can call iterator.remove(); and change loop based on iterator explicitly rather than implicitly.

    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. For-Each 循环
  2. ArrayList Java 文档

这篇关于从数组列表中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆