CS 245 Lab 6 – Generics
First, if you have checkpoints left over from last lab, get them inspected during the first 15 minutes of this lab.
Don’t forget to work in pairs! Where possible, please work with someone that you did not work with last week. The exchange of new ideas and perspectives is not an opportunity you want to rob yourself of.
Synopsis
In this lab, you will explore generalizing code without creating a new, all-encompassing type as we did with interfaces and inheritance. Instead, you will let the type 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: say the past 10 Integers, or the past 5 Strings, or the past 3 Persons, or the past 100 URLs. When you add a new object to the History, if the History has filled up, the oldest item is removed.
Before you write this class, let’s write some JUnit tests. History is a generic class, and we’ll call its generic type T. History will have a constructor that takes in an int for its size, an add method that takes in an instance of type T to add, 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.
Write a few tests that check these methods. Eclipse will be red all over since you haven’t actually written this class or its methods. However, knowledge of the signatures is enough to go on. Recall that a JUnit test suite has this pattern:
public class TestHistory {
@Test
public void testOneItem() {
...
}
@Test
public void testTwoItems() {
...
}
}
You will also need to add JUnit 4 to the build path.
Checkpoint 2
Person B types.
Now, write the History class, with its constructor and methods add and get. The items of the history are of type T. Store the items in an array of type T. Do not use an ArrayList or any other class.
Making an array of a generic type is not as simple as it might seem. As discussed in lecture, you can create an array of Object and cast it to an array of T. The warning can be ignored or suppressed.
If someone tries to get the nth item back in the history, but fewer than n items have been added, throw an IndexOutOfBoundsException.
There are various ways to solve this problem. Some require looping, and some do not require any loops. Choose an implementation that seems sound to you.