/******************************************************************************
* Name: Andy Guna
* NetID: guna
* Precept: P99
*
* Partner Name: N/A
* Partner NetID: N/A
* Partner Precept: N/A
*
* Operating system:
* Compiler:
* Text editor / IDE:
*
* Hours to complete assignment (optional):
*
* A program that demonstrate the use of Iterators and generics. The Bag class (different from algs4)
* implements Iterable. Also the Bag class is a generic class <Item>. The <Item> is
* Initialized by the client Main (in this program as <int>. There are two
* Iterator nested classes are provided, MyIterator and RandomIterator.
* You can try to run the code with each one and see what happens.
*
* To run < java Bag N
* (where N is the Bag size - you provide that)
*
*
******************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
// A different implementation of a Bag different from algs4 Bags implementation
public class Bag<Item> implements Iterable<Item> {
private Item[] a; // array of Items
private int N; // max number of elements in the bag
private int size; // actual number of elements in the bag
public Bag(int N) {
// need cast because Java does not support generic array creation
a = (Item[]) new Object[N];
this.N = N;
this.size = 0;
}
public boolean isEmpty() { return size == 0; }
public int size() { return size; }
public int capacity() { return N; }
// resize the underlying array holding the elements
private void resize(int max) {
Item[] temp = (Item[]) new Object[max];
for (int i = 0; i < N; i++)
temp[i] = a[i];
a = temp;
this.N = max;
}
// insert an item
public void add(Item item) {
if (item == null) throw new NullPointerException();
if (size == a.length) resize(2*a.length); // double size of array if necessary
a[size++] = item; // add element
}
// removes a random item
public Item remove() {
if (isEmpty())
throw new NoSuchElementException("bag is underflow");
Item value = a[--size];
return value;
}
public Iterator<Item> iterator() { return new ReverseIterator(); }
private class ReverseIterator implements Iterator<Item> {
private ; // next item to return
public ReverseIterator() {
}
public boolean hasNext() { }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
}
}
// a test client
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
Bag<Integer> MyBag = new Bag<Integer>(N);
// add N integers
for (int i = 0; i < N; i++) {
MyBag.add(new Integer(i));
}
// iteration
for (int i : MyBag){
for (int j : MyBag) {
StdOut.println(i + " " + j);
}
StdOut.println();
}
}
}