Last active
October 8, 2015 08:22
-
-
Save ekumachidi/30a6aebcb13cae2b7a4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
public ResizingArrayBag() {//initialize an empty array | |
a = (Item[]) new Object[2]; | |
} | |
/*Is this bag empty?*/ | |
public boolean isEmpty() { | |
return N == 0; | |
} | |
/*Size*/ | |
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; | |
} | |
/* Adds the item to this bag. | |
* @param item the item to add to this 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 | |
} | |
/** | |
* Returns an iterator that iterates over the items in the bag in arbitrary order. | |
* @return an iterator that iterates over the items in the bag in arbitrary order | |
*/ | |
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++]; | |
} | |
} | |
/** | |
* Unit tests the <tt>ResizingArrayBag</tt> data type. | |
*/ | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment