A bag is a collection where removing items is not supported—its purpose is to provide clients with the ability to collect items and then to iterate through the collected items.
public interface Bag<Item> extends Iterable<Item>
{
public void add(Item item);
public boolean isEmpty();
public int size();
}
/*************************************************************************
* Compilation: javac ResizingArrayBag.java
* Execution: java ResizingArrayBag
*
* Bag implementation with a resizing array.
*
*************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ResizingArrayBag<Item> implements Iterable<Item> {
private Item[] a; // array of items
private int N = 0; // number of elements on stack
// create an empty bag
public ResizingArrayBag() {
a = (Item[]) new Object[2];
}
public boolean isEmpty() { return N == 0; }
public int size() { return N; }
// resize the underlying array holding the elements
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++)
temp[i] = a[i];
a = temp;
}
// add a new item to the bag
public void add(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
}
public Iterator<Item> iterator() { return new ArrayIterator(); }
// an iterator, doesn't implement remove() since it's optional
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
public boolean hasNext() { return i < N; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i++];
}
}
/***********************************************************************
* Test routine.
**********************************************************************/
public static void main(String[] args) {
ResizingArrayBag<String> bag = new ResizingArrayBag<String>();
bag.add("Hello");
bag.add("World");
bag.add("how");
bag.add("are");
bag.add("you");
for (String s : bag)
StdOut.println(s);
}
}
The implementation is the same as Stack.java except for changing the name of push() to add() and removing pop().
/*************************************************************************
* Compilation: javac Bag.java
* Execution: java Bag < input.txt
*
* A generic bag or multiset, implemented using a linked list.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java Bag < tobe.txt
* size of bag = 14
* is
* -
* -
* -
* that
* -
* -
* be
* -
* to
* not
* or
* be
* to
*
*************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The <tt>Bag</tt> class represents a bag (or multiset) of
* generic items. It supports insertion and iterating over the
* items in arbitrary order.
* <p>
* The <em>add</em>, <em>isEmpty</em>, and <em>size</em> operation
* take constant time. Iteration takes time proportional to the number of items.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class Bag<Item> implements Iterable<Item> {
private int N; // number of elements in bag
private Node first; // beginning of bag
// helper linked list class
private class Node {
private Item item;
private Node next;
}
/**
* Create an empty stack.
*/
public Bag() {
first = null;
N = 0;
assert check();
}
/**
* Is the BAG empty?
*/
public boolean isEmpty() {
return first == null;
}
/**
* Return the number of items in the bag.
*/
public int size() {
return N;
}
/**
* Add the item to the bag.
*/
public void add(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
assert check();
}
// check internal invariants
private boolean check() {
if (N == 0) {
if (first != null) return false;
}
else if (N == 1) {
if (first == null) return false;
if (first.next != null) return false;
}
else {
if (first.next == null) return false;
}
// check internal consistency of instance variable N
int numberOfNodes = 0;
for (Node x = first; x != null; x = x.next) {
numberOfNodes++;
}
if (numberOfNodes != N) return false;
return true;
}
/**
* Return an iterator that iterates over the items in the bag.
*/
public Iterator<Item> iterator() {
return new ListIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
/**
* A test client.
*/
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);
}
}
}