L11

Due by the end of this meeting


SUBMIT   /   Submission Summary

Single Access Container (Interfaces)

Activity 1
Create an interface named SingleAccess. It represents an abstraction over the kinds of containers we discussed last week: Stack, Queue and PriorityQueue (as well as the Hat which was mentioned briefly).

Your interface includes the following methods:

All but the last of these behave exactly as the same-named Queue operations do (some of which are inherited from Collection).

The last is similar to the forEachRemaining method from the Iterator interface. Here is a suitable javadoc for our version:

/** * Performs the given action for each remaining element until all elements * have been processed or the action throws an exception. Actions are * performed in the order of removal, if that order is specified. * Exceptions thrown by the action are relayed to the caller. * <p> * The behavior of the method is unspecified if the action modifies the * container in any way. * <p> * Subsequent behavior is unspecified if the action throws an exception. * * @implSpec * <p>The default implementation behaves as if: * <pre>{@code * while (!isEmpty()) * action.accept(remove()); * }</pre> * * @param action The action to be performed for each element * @throws NullPointerException if the specified action is null */

Provide default definitions for the last three methods listed above.

For your reference, here is the code for Iterator's forEachRemaining method, whose behaviour is pretty much exactly what we want:
default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); }
Activity 2
Wite the Hat class that implements the SingleAccess interface. It remove and poll methods return a randomly-selected object. The methods element and peek throw UnsupportedOperationExceptions with the message Not supported.

Make the methods as efficient as you can. Use an appropriate Java Collection to hold the elements.

Activity 3
Write a program TestHat that uses addAll to add the names Mal, Zoe, Kaylee, Wash, Jayne, Book, Simon, River, Jayne (NOTE: Jayne is there twice) to a Hat, and then uses the forEach method to remove and print each one. (The names should come out in a random order.)

Submit this/these files:


SUBMIT   /   Submission Summary