Exercise 3 - Simulation 3

OOP Design

This exercise is built on Exercise 2 - Simulation 2. And the following are the tasks you should do:

1

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];
    ...
}

Here, Object is used in Line 3 because after type-erasure, T will be replaced by Object. For more information, see Type Erasure from Lec 05.

2

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];
    ...
}

Here, the Comparable in Line 3 is used because after type-erasure, T will be replaced by Comparable. And notice that Comparable itself is a generic type, so actually we are facing two potential problems here. 1) rawtype and 2)unchecked. To solve it, we need to suppress these two potential errors.

3

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!

4

Update Simulation

The last step is to update the simulation workflow accordingly.

The shortest but perhaps the most tedious part of this exercise. 😂

Tips

1

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