【问题标题】:java code optimization when iterate list迭代列表时的java代码优化
【发布时间】:2012-03-02 08:57:48
【问题描述】:

迭代元素列表很常见。检查一些条件并从列表中删除一些元素。

for (ChildClass childItem : parent.getChildList()) {
    if (childItem.isRemoveCandidat()) {
    parent.getChildList().remove(childItem);    
    }
}

但在这种情况下会抛出 java.util.ConcurrentModificationException。

在这种情况下,最好的程序模式是什么?

【问题讨论】:

    标签: java optimization iteration


    【解决方案1】:

    使用Iterator。如果您的列表支持Iterator.remove,您可以改用它! 它不会抛出异常。

    Iteartor<ChildClass> it = parent.getChildList().iterator();
    while (it.hasNext())
        if (it.next().isRemoveCandidat()) 
            it.remove();
    

    注意:ConcurrentModificationException 在您“开始”迭代集合并在迭代期间修改列表时抛出(例如,在您的情况下,它与并发没有任何关系。您正在使用 @987654327迭代期间的@操作,在这种情况下也是如此..)。


    完整示例:

    public static void main(String[] args) {
    
        List<Integer> list = new LinkedList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
    
        for (Iterator<Integer> it = list.iterator(); it.hasNext(); )
            if (it.next().equals(2))
                it.remove();
    
        System.out.println(list); // prints "[1, 3]"
    }
    

    【讨论】:

      【解决方案2】:

      另一种选择是:

      for(int i = parent.getChildList().length - 1; i > -1; i--) {
      
          if(parent.getChildList().get(i).isRemoveCandidat()) {
              parent.getChildList().remove(i);
          }
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用ListItrerator

        for(ListIterator it = list.listIterator(); it.hasNext();){
            SomeObject obj = it.next();
            if(obj.somecond()){
                it.remove();
            }
        }
        

        您也可以使用Iterator。但是ListItrerator 相对于Iterator 的灵活性在于您可以双向遍历列表。

        【讨论】:

          猜你喜欢
          • 2021-07-25
          • 2013-04-17
          • 2010-11-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多