Here's my practice assignment. How should I start it?
The Comparable interface is a very commonly implemented interface. Any class that implements it must define a method called compareTo that compares two objects of that class. If the object that invokes the method is “less than” the object being passed as a parameter, the method returns a negative number. If the object that invokes the method is “greater than” the object being passed as a parameter, the method returns a positive number. If the objects are “equal” the method returns zero. It is up to the programmer to decide what it means for one object to “less than” or “greater than” another object. In this lab, we’re going to extend the return values a bit further and be a little more specific. Each object will be compared based on several criteria (one at a time) to determine comparability. Each non-zero value returned by the compareTo method will indicate where the first determined difference lies. Create a Student class that stores the name, address, GPA, age, and major for a student. Additionally, the Student class should implement the Comparable interface. Make the comparison of Student objects based on the name, then the address, then the major, and finally the GPA. If the difference between two objects when compared lies in the name, return a 1 or -1 depending on which object is lessor/greater. If the difference in objects is in the address, return +/- 2. If the difference is in the major, return +/- 3. If the difference is in the GPA, return +/- 4. Only return zero if all 4 fields are the same. This behavior deviates slightly from the normal compareTo behavior (<0, 0, or >0), but we are ok with that for the purposes of this lab. Write a class called StudentDriver to test your new method. Hard code several students into the main method of the StudentDriver class with small differences in different fields. That is, make one student have one name and another a second name. Make a third student have the same name as the first, but a have the third student have a different address, etc. Make sure your compareTo method finds each the differences correctly.
Implement the interface by passing an Object into the compareTo method and to cast the object parameter into the desired type – in this case a Student object).
An example of this approach (note the parameter passing and
casting) would be as follows:
public int compareTo(Object anotherPerson) throws ClassCastException {
if (!(anotherPerson instanceof Person))
throw new ClassCastException("A Person object is expected by this compareTo.");
int anotherPersonAge = ((Person) anotherPerson).getAge();
return this.age - anotherPersonAge;
}
IDEAS/HELP PLEASE?!