public class ModificationCrash
1: import java.util.ArrayList;
2: import java.util.List;
4: /**
5: * A program that CRASHES because of a ConcurrentModification.
6: *
7: * @author Mark Young (A00000000)
8: */
9: public class ModificationCrash {
11: public static void main(String[] args) {
12: List<Double> myNumbers = new ArrayList<Double>();
14: // Introduce
15: System.out.println("\n"
16: + "Failed attempt to remove negative numbers from a list\n");
18: // create the list
19: myNumbers.add(20.5);
20: myNumbers.add(42.0);
21: myNumbers.add(40.2);
22: myNumbers.add(-5.3);
23: myNumbers.add(-8.0);
24: myNumbers.add(0.0);
25: myNumbers.add(15.1);
26: myNumbers.add(-30.7);
27: myNumbers.add(42.5);
28: System.out.println("Original list: " + myNumbers);
30: // remove all negative numbers
31: // NOTE: THIS CODE CRASHES!!!
32: for (double num : myNumbers) {
33: if (num < 0.0) {
34: myNumbers.remove(num);
35: }
36: }
38: // print result (we won't make it to here!)
39: System.out.println("After removing negatives: " + myNumbers);
40: System.out.println("\nHuh???\n");
41: }
43: }