CS 161 Lab 7


This lab will cover interfaces and the Java compareTo interface.

Lab Demo

The Java Comparable interface

Sorting is one of the most common tasks to perform on data. Java provides Arrays.sort() as a tool for sorting arrays of common Java types. Here are some examples of what you can do: But what if you want to sort objects that belong to a class that you have written yourself? Turns out there's an easy way to do so! All you need to do in order to use Arrays.sort is to implement the Comparable interface which requires you to implement a compareTo method. More specifically, we will sort objects belonging to a class called Student. Students will be sorted first by whether they are an undergraduate or not (undergraduates go first), then by their GPA (higher first), then by their name (lexicographically). Follow along in the demo to see how it's done.

You will need the following file:

Lab Assignment

Think of an interface as a contract: a class that implements an interface commits to implementing a given list of methods. It has complete freedom on how to do it, and can implement other methods as well. We'll create three classes:

All three classes will implement the Searching interface, which has a single method called search.

LinearSearch simply goes through the array from the start and returns the index of the first occurrence of the number that you are searching for if it exists in the array, otherwise returns -1.

RandomSearch is pretty interesting. It just tries five times to locate the number by trying indices randomly. If it doesn't find it in these five attempts, it gives up and says the number is not there. It is recommended that you use a Random object instead of using Math.random(). The random object will pick a number in the given range every time it is called and therefore it will occasionally guess the same number more than once. For an extra challenge, can you keep your random method from guessing the same number twice?

BinarySearch performs the same functionality, but uses the binary search method, which was covered when we discussed recursion. It assumes the array is sorted; it uses a helper function which receives a range of indices as input, one for the beginning of the range where you are searching for the number, one for the end; it then computes the middle of the range. If the number in the middle of the range is the number you are looking for, great! If not, what do you need to change your range to? When would you stop searching for the number?

You will need the following files for this part: