Source of ModificationError.java


  1: import java.util.ArrayList;
  2: import java.util.List;

  4: /**
  5:  * A program that tries (but fails) to remove all negative numbers from a list.
  6:  *
  7:  * @author Mark Young (A00000000)
  8:  */
  9: public class ModificationError {

 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 WON'T WORK!!!
 32:         for (int i = 0; i < myNumbers.size(); i++) {
 33:             double num = myNumbers.get(i);
 34:             if (num < 0.0) {
 35:                 myNumbers.remove(i);
 36:             }
 37:         }

 39:         // show the (wrong!) results
 40:         System.out.println("After removing negatives: " + myNumbers);
 41:         System.out.println("\nHuh???\n");
 42:     }

 44: }