The goal of this assignment is to perform searching operations (min, max, kmin, kmax) from a generic collection using a Comparator. The collection and Comparator are passed into the methods as
A common question is where do we get the
comp. The answer is the user (client) of your class will supply both parameters and your responsibility is to make sure your class return correct values based on the parameters. In other words, when Web-Cat checks your code, it will pass in both
comp will be passed in for you, as you write your code, you also need to check the correctness of your code; therefore, when you test your code, you become the user of your class and you have to write your own Comparators to use in test cases.
This note shows how to use and write Comparators for this assignment.
comp is an instance of a Comparator class. As noted previously, the
Comparator determines which element is greater than or less than the other.
The writer of the Comparator class decide the meaning of “greater than” and “less than”. This means that if they want, the writer of Comparator can make a smaller number “greater than” a number that is bigger.
The following example finds the minimum using a Comparator.
To test your code, you should write your own Comparators. For each way of comparing a collection, you should write a
Comparator class. Here we’re going to write two integer Comparators, one ascending one descending, and one Comparator for the
Data class below, which has 2 fields. For each please create a new
.java file, with the same name as your class.
The following code shows an integer ascending Comparator (AscIntComparator.java).
The following code shows an integer ascending Comparator (DescIntComparator.java).
Note that the only difference between the two classes is the reversal of the return values. In other words, if we sort using the
DescIntComparator class, we would get a reversely sorted array.
The following shows the
Data class and corresponding Comparator.
Writing jUnit Test Cases
The following is an example test case for the min method.