hi everybody! i need help basically figuring out how to start this assignment using the comparable interface:
1. 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.
Note that there are two approaches to implementing the interface:
• one using Java generics – we’ll talk about generics in a few lectures,
• the other to pass an Object into the compareTo method and to cast the object parameter into
the desired type – in this case a Student object).
For this assignment, use the latter approach. 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;
}
any ideas??!