teaching machines

CS 245 Lab 8 – Generic History

First, if you have checkpoints left over from last lab, get them inspected during the first 15 minutes of this lab. No credit will be awarded past these 15 minutes.

Work in pairs, where possible. Prefer working with someone that you did not work with last lab. The exchange of new ideas and perspectives is not an opportunity you want to rob yourself of.


In this lab, you will write a class for storing a finite history of data. You find histories in many places. For example, your browser tracks a history of the pages you’ve visited, your fancier calculator track a history of the expressions you’ve entered, and your cell phone tracks a history of numbers you’ve dialed.

We’ll explore generalizing code without creating a new, all-encompassing type as we did with interfaces and inheritance. Instead, you will let the type of item stored in the history be a parameter to your code. Crazy!

Checkpoint 1

Person A types.

In Checkpoint 2, your task is to write a class named History. This class will keep a fixed-size collection of objects: perhaps the past 10 Integers, or the past 5 Strings, or the past 3 Persons, or the past 100 URLs. If you add a new object to a full History, the oldest item is removed.

Write just the skeleton of the History class. Do not write complete method bodies or add any instance variables. Do as little as possible to make the code compile. Make History a generic class. Give it

  1. a constructor that takes in an int for its capacity,
  2. a size method that reports how many items are in the history,
  3. an add method that takes in an instance of type T to add,
  4. and a get method that takes in an int. A call to get(0) returns the most recently added item, get(1) the second most recently added, get(2) the third most recently added, and so on.

With the skeleton in place, let’s write some JUnit tests. Knowledge of what the class is supposed to do is enough to go on. Recall that a JUnit test suite has this pattern:

public class TestHistory {
  public void testOneItem() {

  public void testTwoItems() {

Use Assert.assertEquals to test the code. You will also need to add JUnit 4 to the build path.

Checkpoint 2

Person B types.

Now, fully implement History. Store the items in an array of type T. Do not use an ArrayList or any other class.

If someone tries to get the nth item back in the history, but fewer than n items have been added, throw a NoSuchElementException.


Leave a Reply

Your email address will not be published. Required fields are marked *