Exercise 3 - Simulation 3
OOP Design
This exercise is built on Exercise 2 - Simulation 2. And the following are the tasks you should do:
Make Queue a generic class
This means that you should define your Queue with the generic type parameter, which means that the elements in the queue should be of type T.
public class Queue<T> {
...
}Since the queue is supposed to store an array of elements with type T. Inside the class constructor, after making sure we can only add element of type T into the queue, we should do the following
public Queue(int size) {
@SuppressWarnings("unchecked")
T[] items = (T[]) new Object[size];
...
}Create a generic Seq<T> class
Since in this exercise, we want to further make our code generalizable. That is, we don't want to use Counter[] counters in exercise 2 to explicitly state that bank has counters. Why not we define our own comparable "array" with a generic type parameter? To do so, we should define Seq as follows,
class Seq<T extends Comparable<T>> {
...
}Similarly, we want our Seq to store an array of comparable elements. Thus, in our constructor, after we make sure that we can only add element of type T that is comparable into the queue, we should do the following,
public Seq (int size) {
@SuppressWarnings({"rawtypes", "unchecked"})
T[] a = (T[]) new Comparable[size];
...
}Make Counter Comparable to Itself
As we want to use Seq<T extends Comparable<T>> to repalce the Counter[] in our bank, the type T we pass in must be comparable! That is to say, our Counter class must implement the Comparable<Counter>!
class Counter implements Comparable<Counter> {
...
}This is to make Counter comparable!
Update Simulation
The last step is to update the simulation workflow accordingly.
Tips
Instantiate the generic type
In this exercise, one thing that may be confused is that, Queue and Seq actually are not arrays! So, to initialize them, we can simply use
Queue<Customer> q = new Queue<Customer>(size);
Seq<Counter> s = new Seq<Counter>(size);This doesn't violate the principle that "generic types and arrays cannot mix". Essentially, it's just we have dealt with this problem inside the Queue and Seq class.
Last updated