Source of ClassWithList.java


  1: import java.util.ArrayList;
  2: import java.util.Collections;
  3: import java.util.List;
  4: import java.util.Objects;

  6: /**
  7:  * A named class to hold non-negative numbers.
  8:  * 
  9:  * @author Mark Young (A00000000)
 10:  */
 11: public class ClassWithList {
 12:     
 13:     private String name;
 14:     private List<Integer> myNumbers;
 15:     
 16:     /**
 17:      * Create an empty list.
 18:      * 
 19:      * @param reqName the name for this list
 20:      */
 21:     public ClassWithList(String reqName) {
 22:         name = reqName;
 23:         myNumbers = new ArrayList<>();
 24:     }
 25:     
 26:     /**
 27:      * Get the name of this list.
 28:      * 
 29:      * @return the name of this list
 30:      */
 31:     public String getName() {
 32:         return name;
 33:     }
 34:     
 35:     /**
 36:      * Change the name of this list.
 37:      * 
 38:      * @param newName the new name for this list
 39:      */
 40:     public void setName(String newName) {
 41:         name = newName;
 42:     }
 43:     
 44:     /**
 45:      * Add another number to this list. NOTE: the number must not be negative.
 46:      * 
 47:      * @param newNum the number to add
 48:      * @throws IllegalArgumentException if the number is negative
 49:      */
 50:     public void add(int newNum) {
 51:         if (newNum < 0) {
 52:             throw new IllegalArgumentException("Negative numbers not allowed");
 53:         }
 54:         myNumbers.add(newNum);
 55:     }
 56:     
 57:     public boolean remove(int oldNum) {
 58:         // need to create an Integer object to use remove-by-value
 59:         return myNumbers.remove(Integer.valueOf(oldNum));
 60:     }
 61:     
 62:     /**
 63:      * A VERY BAD IDEA!!! Allows the client to mess with the List!
 64:      * 
 65:      * @return the ACTUAL LIST this object contains
 66:      */
 67:     public List<Integer> getNumbersForCheater() {
 68:         return myNumbers;
 69:     }
 70:     
 71:     /**
 72:      * A MUCH BETTER IDEA! Does not allow the client to change the list!
 73:      * 
 74:      * @return a view of the list this object contains
 75:      */
 76:     public List<Integer> getNumbersSafely() {
 77:         return Collections.unmodifiableList(myNumbers);
 78:     }
 79:     
 80:     @Override
 81:     public String toString() {
 82:         return name + ": " + myNumbers;
 83:     }
 84: }