Due Date:
Friday, February 16
File(s) to be submitted:
LinkedBag.java
Sample Output:
SampleOutput.html
Starter Files:
Summary
Complete the definition of theiterator
method in the LinkedBag class. The implementation will require you to create a private class that implements the Iterator<E> interface.Test your implementation using the A05 program provided.
The sample implementation of LinkedBag
is missing definitions for five methods.
(Actually, there are definitions,
but each one throws an UnsupportedOperationException.)
You are to complete the definition of
iterator
(skip the other four).
The iterator
method
returns an Iterator<E>,
where E is the base type of the Bag.
(Thus,
if it's a bag of Integer,
the object returned will be an Iterator<Integer>;
if it's a bag of String,
the object returned will be an Iterator<String>.)
But Iterator is an interface,
so you'll need to create a class that implements that interface.
Create a private class named LinkedBagIterator
in your LinkedBag class.
The Iterator interface requires two methods:
hasNext()
-- which checks whether there are more elements to visit; and
next()
-- which returns the next element visited.
Note: you do not need to implement any other public methods in the Iterator interface. Those other methods (remove()
andforEachRemaining(...)
) have suitable default implementations.You also should not implement any of the other ListIterator methods (such as
previous
andset
). Those methods are not part of the Iterator interface.
There are two Exceptions that might be thrown by the methods in your private class.
next()
if the client tries to get data after the last element of the chain.
next()
and hasNext()
if they notice that the size of the Bag has changed.
If the size of the Bag changes, that means that an element has been added or removed, and under those circumstances the elements of the Bag might have moved (for a removal) or be where they're no longer reachable (for an add). In either case, there may now be elements in the Bag that the Iterator can't visit.Since the point of the iterator is to allow all elements of the Bag to be visited, that's a problem!
You should write a private method in your private class to check whether the size of the Bag has changed, and throw a ConcurrentModificationException if so.
Think about what information your Iterator object
is going to need in order to do its job.
Keep in mind that the LinkedBagIterator class
is defined inside the LinkedBag class,
so unless you make the private class static
(don't do that),
it'll have access to its Bag's instance variables.
You won't need to use any of the methods defined in LinkedBag.
Do not modify any parts of LinkedBag other than the iterator method and the private class I'm asking you to create..