X484: Array Bag Practice 2

For the following question, assume the following class definition of ArrayBag and item

public static final class ArrayBag<T>  {
    private T[] contents;
    private static final int MAX = 25;
    private int numberOfEntries;

    @SuppressWarnings("unchecked")
    public ArrayBag() {
        T[] tempBag = (T[])new Object[MAX];
        contents = tempBag;
        numberOfEntries = 0;
    }

    public ArrayBag(int desiredCapacity) {
        @SuppressWarnings("unchecked")
        // Unchecked cast
        T[] tempBag = (T[])new Object[desiredCapacity];
        contents = tempBag;
        numberOfEntries = 0;
    } // end constructor

    public boolean isEmpty() {
        return getCurrentSize() == 0;
    }

    public boolean add(T anEntry) {
        if (anEntry == null) {
            return false;
        }
        if (numberOfEntries < contents.length) {
            contents[numberOfEntries] = anEntry;
            numberOfEntries++;
            return true;
        }
        else {
            return false;
        }
    }
  }
public static class Item{
    private String name;
    private double price;
    private boolean isOnSale;

    public Item(String n, double p, boolean sale) {
        name = n;
        price = p;
        isOnSale = sale;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public boolean getIsOnSale() {
        return isOnSale;
    }

}

For this question, write a method that will take in an arraybag of Item objects. Remove all the Item objects that are not on sale.

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.