X816: Array Bag Practice 1
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 onSale;
public Item(String n, double p, boolean sale) {
name = n;
price = p;
onSale = sale;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public boolean getOnSale() {
return onSale;
}
}
For this question, write a method that will take in an array of Item objects. Create an ArrayBag of Item objects and add all of the items where onSale
is true
, then return the ArrayBag.
Your Answer:
Feedback
Your feedback will appear here when you check your answer.