/** * An implementation of the BagOfPets Interface * * Note that everything marked with @Override does not need documentation as it * should be documented elsewhere. * @author gtowell * Created: July 2021 * */ public class StuffBag implements BagOfStuff { /** The array holding the information in the bag */ private R[] stuffArray; /** * The default constructor. * Creates a bag that can hold 100 stuff. */ public StuffBag() { this(100); } /** * Constructor for stuff bag * param sizeOfBag is the size of the bag */ @SuppressWarnings("unchecked") public StuffBag(int sizeOfBag) { stuffArray = (R[])new Object[sizeOfBag]; } @Override public int numberOfItems() { int count = 0; for (int i = 0; i < stuffArray.length; i++) { if (stuffArray[i] != null) count++; } return count; } @Override public boolean isEmpty() { return numberOfItems() == 0; } @Override public boolean add(R p) { int loc=0; while (loc < stuffArray.length && stuffArray[loc] != null) { loc++; } if (loc == stuffArray.length){ return false; } else { stuffArray[loc] = p; return true; } } @Override public R remove() { int loc=0; while (loc < stuffArray.length && stuffArray[loc] == null) { loc++; } if (loc == stuffArray.length){ return null; } else { R tmp = stuffArray[loc]; stuffArray[loc] = null; return tmp; } } @Override public boolean remove(R p) { boolean found = false; for (int i = 0; i < stuffArray.length; i++) { if (stuffArray[i] == p) { found = true; stuffArray[i] = null; } } return found; } @Override public void clear() { for (int i = 0; i < stuffArray.length; i++) { stuffArray[i] = null; } } @Override public int countOf(R p) { int count = 0; for (int i = 0; i < stuffArray.length; i++) { if (stuffArray[i] == p) { count++; } } return count; } @Override public boolean contains(R p) { return countOf(p) > 0; } @Override public R getInstance(R p) { for (int i = 0; i < stuffArray.length; i++) { if (stuffArray[i].equals(p)) { return stuffArray[i]; } } return null; } @Override public void display() { System.out.println(toString()); } @Override public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < stuffArray.length; i++) { if (stuffArray[i] != null) { sb.append(stuffArray[i].toString()); sb.append("\n"); } } return sb.toString(); } }