Write a class called MyBag that implements the Bag interface: public interface B
ID: 3847509 • Letter: W
Question
Write a class called MyBag that implements the Bag interface:
public interface Bag<T> extends Iterable<T>
{
public boolean isEmpty();
public int size();
public void add(T item);
}
Your MyBag implementation should use the Java ArrayList to implement the Bag interface.
Any change made to the Bag interface or using a data structure/implementation other than an ArrayList will result in a grade of 0.
Write a driver that tests your MyBag class. Be sure to include a for-each loop to print all the items in the bag.
Explanation / Answer
implementation of the the Bag interface
public interface Bag<T> extends Iterable<T> {
public int size();
public boolean add(T x);
public T remove(T x);
public T find(T x);
public void clear();
}
//Implementing thing using bag
public class Bag<T> implements Bag<T> {
private ArrayList<T> list = new ArrayList<T>();
public boolean isEmpty() {
return first == null;
}
@Override
public int size() {
return list.size();
}
public void add(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
@Override
//remove method returns T
//Sine you already pass x of type T as parameter
public T remove(T x) {
list.remove(x);
return x;
}
}
public static void main(String[] args) {
Bag<String> bag = new Bag<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
bag.add(item);
}
StdOut.println("size of bag = " + bag.size());
for (String s : bag) {
StdOut.println(s);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.