/** * 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 PetBag implements BagOfPets { /** The array holding the information in the bag */ private Pet[] petArray; /** * The default constructor. * Creates a bag that can hold 100 pets. */ public PetBag() { this(100); } /** * Constructor for pet bag * param sizeOfBag is the size of the bag */ public PetBag(int sizeOfBag) { petArray = new Pet[sizeOfBag]; } @Override public int numberOfItems() { int count = 0; for (int i = 0; i < petArray.length; i++) { if (petArray[i] != null) count++; } return count; } @Override public boolean isEmpty() { return numberOfItems() == 0; } @Override public boolean add(Pet p) { int loc=0; while (loc < petArray.length && petArray[loc] != null) { loc++; } if (loc == petArray.length){ return false; } else { petArray[loc] = p; return true; } } @Override public Pet remove() { int loc=0; while (loc < petArray.length && petArray[loc] == null) { loc++; } if (loc == petArray.length){ return null; } else { Pet tmp = petArray[loc]; petArray[loc] = null; return tmp; } } @Override public boolean remove(Pet p) { boolean found = false; for (int i = 0; i < petArray.length; i++) { if (petArray[i] == p) { found = true; petArray[i] = null; } } return found; } @Override public void clear() { for (int i = 0; i < petArray.length; i++) { petArray[i] = null; } } @Override public int countOf(Pet p) { int count = 0; for (int i = 0; i < petArray.length; i++) { if (petArray[i] == p) { count++; } } return count; } @Override public boolean contains(Pet p) { return countOf(p) > 0; } @Override public void display() { System.out.println(toString()); } @Override public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < petArray.length; i++) { if (petArray[i] != null) { sb.append(petArray[i].toString()); sb.append("\n"); } } return sb.toString(); } }