如何在Java的字符串列表中删除元素? [英] How can i remove an element in a string list in java?

查看:273
本文介绍了如何在Java的字符串列表中删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所见,我想从我的SplitedIgrediants列表中删除或删除等于我的成分ID的成分,所以我尝试了删除或删除,但它出现了错误.因此,我该怎么做才能从JAVA列表中删除这种成分.

As u can see i wanna delete or remove the ingrediant which equals my ingredientid from my SplitedIgrediants list, i've tried with remove or delete but it's appear an error. So how can i do to delete this ingredient elemant please from my list in JAVA.

        String ingredientid = request.getParameter("id");
        DbHandler dbsplt = new DbHandler();
        for (String ingrediant : SplitedIngrediants) {
            if (ingrediant.equals(ingredientid)) {
                //HERE REMOVE THE ingredient from SplitedIngrediants list
            }

推荐答案

除非您手动声明iterator并使用.

You cannot remove elements from a Collection while iterating on it (you will get some ConcurrentModificationException) except if you manually declare the iterator and use iterator.remove().

示例:

List<Integer> list = new ArrayList<Integer>();

list.add(3);
list.add(4);
list.add(5);

Iterator<Integer> it = list.iterator();
Integer current;
while (it.hasNext()) {
    current = it.next();
    if(current.equals(4)) {
        it.remove();
    }
}

输出:

[3, 5]

其背后的原因是"foreach"构造在内部创建了一个迭代器.迭代器的目的是确保可迭代对象的每个元素都被精确地访问一次.因此,如果您在不使用迭代器方法的情况下从可迭代对象中添加/删除元素,则迭代器将无法再完成其任务.

The reason behind that is that the "foreach" construction internally creates an iterator. The aim of the iterator is to ensure that each element of the iterable is visited exactly once. So if you add/remove elements from the iterable without using the iterator methods, the iterator can no longer fulfil its task.

第二个选项:在列表上进行迭代时,列出要删除的项目,并在迭代后将其删除.

2nd option : while iterating on the list, make a list of the items to delete and delete them after iterating.

这篇关于如何在Java的字符串列表中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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