Created
October 18, 2012 03:25
-
-
Save mpilquist/3909703 to your computer and use it in GitHub Desktop.
Don't mutate stuff while iterating
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scala> val s = MSet() ++ (1 to 20) | |
s: scala.collection.mutable.Set[Int] = Set(5, 9, 15, 16, 18, 14, 19, 2, 20, 6, 1, 13, 4, 12, 7, 3, 8, 17, 11, 10) | |
scala> s.size | |
res16: Int = 20 | |
scala> s foreach { n => if (n % 2 == 0) s -= n } | |
scala> s.size | |
res18: Int = 11 | |
scala> s | |
res19: scala.collection.mutable.Set[Int] = Set(15, 9, 18, 19, 1, 13, 17, 7, 3, 11, 5) | |
scala> s foreach { n => if (n % 2 == 0) s -= n } | |
scala> s.size | |
res21: Int = 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ignore the fact that this can be done with calling filter on the set. The point here is that ConcurrentModificationException does not occur and instead, the foreach silently skips elements.