简体   繁体   中英

how to use the iterator in if -else loop with removeAll in java?

I have the following problem: I do use iterator in the first part of "if" to remove an element of S, but I don't have a clue about how to remove the whole set S3 from S using the same iterator again in the "else" part. Any ideas? Thank you in advance!

public void f(RewritingNode x, Set<RewritingNode>S0){
      Set<RewritingNode> S1 = new HashSet<RewritingNode>();
      Set<RewritingNode> S3 = new HashSet<RewritingNode>();
      S1.addAll(x.children);
      S0.addAll(S1);
      Set<RewritingNode> S = new HashSet<RewritingNode>();
      S.addAll(S1);

      while (!S.isEmpty()){
          for (Iterator<RewritingNode> iter_y= S.iterator(); iter_y.hasNext();) {
              RewritingNode y = iter_y.next();

              RewritingNode y = iter_y.next();

              if(S0.containsAll(y.parents)||y.parents.isEmpty()){
                 iter_y.remove();
              }
              else {
                  S3.add(y);                      
                  S.addAll(S1);             
                  S.removeAll(S3);
              } 
          }
    }

    Set<RewritingNode> removedChildren = new HashSet<RewritingNode>();
    removedChildren.addAll(S1);
    removedChildren.removeAll(S3);

    for(RewritingNode x1 :removedChildren){
        x1.parents.removeAll(x1.parents);
        f(x1,S0);
    }
}

Put all the elements you want to remove in a separate list or set and remove them after your loop finishes. In the case of remove all, set a boolean and again, do this after the while-loop ends. Or just add all the element to your remove elements list and remove them after the while loop ends otherwise you'll get some sort of concurrent modification exception.

Update

Try to use a queue instead of whatever you are doing here. A queue like LinkedList which has a FIFO order. LinkedList has a remove() method which returns the first element and removes it. Use it to fetch the first element and compare it, if you need to keep it, add it to the list again and it'll become the last element. keep doing this till the list is empty and that should do it for you.

This should be far simpler than your code and no need for iterators or multiple sets. If for whatever reason you do need to add removed elements to a set (or event he ones you want to keep) when the remove() method returns the element, add it to whatever set you want.

使用带索引而不是迭代器或增强For循环的正常For循环,我认为你在通过迭代器时不能执行removeAll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM