开发者

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();

              Rewri开发者_Python百科tingNode 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.


Use a normal For loop with index instead of iterator or enhanced For loop, I think you cannot do removeAll while going through an iterator

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜