CS 161 Lab 11

Overview

This lab will cover interfaces and the Java compareTo interface.

Lab Demo

The Java compareTo 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 is 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 a class called Student. Students will be sorted first by whether they are an undergraduate or not (undergraduates go first), then by their GPA, then by their name. Follow along in the demo to see how it's done.

You will need the following files in addition:

Lab Assignment

Think of an interface as a contract - a class that implements an interface commits to implementing a given list of methods. At 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 Search interface, which has a single method called search.

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

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?

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()

You will need the following files for this part: