-1

During iteration, removal is not allowed from a collection. I have a piece of code that is working which i thought should not work. Can it fail in future and why is it working right now?

public class RemoveFromSet {

    static Set<Integer> set = new HashSet<>();
    public static void main(String[] args) {
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(4);
        while(set.size()>0) {
            int val = set.iterator().next();
            set.remove(val);
            System.out.println("removed val = "+val);
        }
    }

}
lospejos
  • 1,976
  • 3
  • 19
  • 35
curiousengineer
  • 2,196
  • 5
  • 40
  • 59
  • 2
    Possible duplicate of [Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – MordechayS Oct 31 '16 at 20:45

3 Answers3

5

Actually this should work as your first line in the loop retrieves a brand new iterator each iteration. Now if you used the iterator after the remove you would have a problem.

Eelke
  • 20,897
  • 4
  • 50
  • 76
1

Usually when you want to remove elements from a collection in a loop you use an Iterator. An example in your case would be:

Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
    Integer element = iterator.next();
    iterator.remove();
    System.out.println("Removed val = " + element);
}

As other answers have pointed out, you are getting a new iterator each loop which is why you aren't getting an error.

Scooter
  • 1,031
  • 1
  • 14
  • 33
0

Your loop is not an iteration of a collection. The for condition doesn't rely on an iterator.
The iterator created at each inside the loop is independent of the for condition since created inside the loop and besides you don't iterate on that iterator : you create that at each iteration and take just first value.

It would fail if you really iterate on the collection with an iterator for example :

  public static void main(String[] args) {
    set.add(1);
    set.add(2);
    set.add(3);
    set.add(4);
    for (Iterator iterator = set.iterator(); iterator.hasNext();) {
        Integer integer = (Integer) iterator.next();
        set.remove(integer);
        System.out.println("removed val = " + integer);
    }
  }
davidxxx
  • 125,838
  • 23
  • 214
  • 215