title: Java, multiple iterators on a set, removing proper subsets and ConcurrentModificationException
body: <p>I have a set A = {(1,2), (1,2,3), (2,3,4), (3,4), (1)}</p>
  
  <p>I want to turn it into A={(1,2,3), (2,3,4)}, remove proper subsets from this set.</p>
  
  <p>I'm using a HashSet to implement the set, 2 iterator to run through the set and check all pairs for proper subset condition using containsAll(c), and the remove() method to remove proper subsets.</p>
  
  <p>the code looks something like this:</p>
  
  <pre><code>HashSet&lt;Integer&gt; hs....
  Set&lt;Integer&gt; c=hs.values();
  Iterator&lt;Integer&gt; it= c.iterator();
  while(it.hasNext())
  {
      p=it.next();
      Iterator&lt;Integer&gt; it2= c.iterator();
      while(it2.hasNext())
      {
          q=it2.next();
          if q is a subset of p
              it2.remove();
          else if p is a subset of q
          {
              it.remove();
              break;
          }
      }
  }
  </code></pre>
  
  <p>I get a ConcurrentModificationException the 1st time i come out of the inner while loop and do a </p>
  
  <pre><code>p=it.next();
  </code></pre>
  
  <p>The exception is for when modifying the Collection while iterating over it. But that's what .remove() is for.</p>
  
  <p>I have used remove() when using just 1 iterator and encountered no problems there.</p>
  
  <p>If the exception is because I'm removing an element from 'c' or 'hs' while iterating over it, then the exception should be thrown when it encounter the very next it <strong>2</strong> .next() command, but I don't see it then. I see it when it encounters the it.next() command.</p>
  
  <p>I used the debugger, and the collections and iterators are in perfect order after the element has been removed. They contain and point to the proper updated set and element. it.next() contains the next element to be analyzed, it's not a deleted element.</p>
  
  <p>Any ideas over how i can do what i'm trying to do without making a copy of the hashset itself and using it as an intermediate before I commit updates?</p>
  
  <p>Thank you</p>