无法从ArrayList中删除 [英] Not able to remove from an ArrayList

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

问题描述

 import java.util;  
 class Driver{

 public static void main(String[] args) {
      ArrayList<String> lstStr = new ArrayList<String>();
      lsstStr.add("A");
      lsstStr.add("B");
      lsstStr.add("C");
      for(Iterator<String> it = lstStr.Iterator(); it.hasNext();)
      {
          str = it.next();
          if(str.equals("B")){lstStr.remove(str);}
      }
      for(Iterator<String> it = lstStr.Iterator(); it.hasNext();)
      {
        System.out.println(it.next());
      }
 }
 }

这不是删除B 从列表中。当循环第二次运行时为什么Str不等于B。为什么?

This is not removing "B" from the list. Why Str is not equal to "B" when loop runs second time.Why?

推荐答案

你不能从中删除一个项目你正在使用除之外的集合%29rel =nofollow> Iterator.remove - 您将获得 ConcurrentModificationException 。所以你的循环将是这样的:

You can't remove an item from a collection you're iterating over except using Iterator.remove - you'll get a ConcurrentModificationException. So your loop would be something like:

for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String value = iterator.next();
    if (value.equals("B")) {
        iterator.remove();
    }
}

当然,你应该使用 removeAll 只是删除具有特定值的所有项目 - 但如果您需要根据除简单相等之外的某些条件删除,则使用上述方法(例如, 删除长度大于5的所有值。另一个选项是收集要在新集合中删除的所有值,然后再调用 removeAll

Of course, you should use removeAll to just remove all items with a specific value - but the above approach is the one to use if you need to remove based on some condition other than simple equality (e.g. "remove all values with a length greater than 5". Another option is to collect all the values to remove in a new collection, and then call removeAll afterwards.

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

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