L08

Due by the end of this meeting

Starter Files:


SUBMIT   /   Submission Summary

Array Implementations

Activity 1
Download the class ArrayBag along with the interface Bag and the testing program TestIterator.

Revise ArrayBag by implementing the iterator method.

The implementation requires you to make a private class named BagIterator that implements Iterator<T> inside the ArrayBag class.

Do not make the private class static. By making it an "instance class" it can refer to elements of the ArrayBag that created it. In particular, it can talk about numInBag and contents without needing to specify which ArrayBag they're part of. They automatically refer to the fields of the correct ArrayBag.

Also, because it is an instance class, it has access to the type parameter T, so you don't need to re-introduce that parameter.

A BagIterator is an object that lets a client iterate thru the elements of this Bag. The BagIterator class has the following methods:

A BagIterator is used like any other Iterator:

Iterator<String> it = wordBag.iterator(); while (it.hasNext()) { String word = it.next(); System.out.println("There is a \"" + word + "\" in the Bag"); }

Run the program TestIterator program to ensure that your iterator loop works. If you've done everything correctly, you should see something like this:

Here is the bag: [This, is, the, bag] There is a "This" in the Bag There is a "is" in the Bag There is a "the" in the Bag There is a "bag" in the Bag There is nothing more in the Bag OK, now there is a "extended" in the Bag There is no null in the Bag, so this line should NOT get printed! You may be ready for Activity 2

NOTE that it's fine if you see this instead:

Here is the bag: [This, is, the, bag] There is a "bag" in the Bag There is a "the" in the Bag There is a "is" in the Bag There is a "This" in the Bag There is nothing more in the Bag Didn't notice the extra thing in the bag... There is no null in the Bag, so this line should NOT get printed! You may be ready for Activity 2
Activity 2
Revise the next method so that it throws a NoSuchElementException if all of there are no more items to return.

Once you have completed the implementation, your output may look like this:

Here is the bag: [This, is, the, bag] There is a "This" in the Bag There is a "is" in the Bag There is a "the" in the Bag There is a "bag" in the Bag There is nothing more in the Bag OK, now there is a "extended" in the Bag Got the expected exception

Alternatively, it may look like this:

Here is the bag: [This, is, the, bag] There is a "bag" in the Bag There is a "the" in the Bag There is a "is" in the Bag There is a "This" in the Bag There is nothing more in the Bag Didn't notice the extra thing in the bag... Got the expected exception

Submit this/these files:


SUBMIT   /   Submission Summary