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