import java.util.LinkedList; import java.util.ListIterator; import java.util.Random; /** BagLinkedList.java -- Here is a 2nd implementation of a bag, using * a Java LinkedList for our Items instead of an ArrayList. * We'll use inheritance to save us having to define functions that * already exist exactly how we want. For example, LinkedList already has * methods for add, remove and size. */ public class BagLinkedList extends LinkedList { private LinkedList list; // remove a random object -- one thing that does not come public Item remove() { Random gen = new Random(); int index = gen.nextInt(this.size()); return (Item) this.remove(index); } // Assume b is a linked list. For each element in b, add it to myself. public BagLinkedList combine(BagLinkedList b) { // Have the LinkedList class return an iterator for b. ListIterator iterator = ((BagLinkedList) b).listIterator(0); while (iterator.hasNext()) add(iterator.next()); return this; } public boolean equals(BagInterface b) { return this.equals((BagLinkedList) b); } public void give(Item i, BagInterface b) { this.remove(i); ((BagLinkedList) b).add(i); } public String toString() { StringBuilder build = new StringBuilder(); ListIterator iterator = this.listIterator(0); while (iterator.hasNext()) { build.append("\t" + iterator.next().toString() + "\n"); } return build.toString(); } }