Modify the Student class in Listing 8.2 so that it implements the comparable interface. Define the compareTo
Question:
Modify the Student class in Listing 8.2 so that it implements the comparable interface. Define the compareTo method to order Student objects based on the value in studentNumber. In a main method create an array of at least five Student objects, sort them using Arrays.sort, and output the students. They should be listed by ascending student number. Next, modify the compareTo method so it orders Student objects based on the lexicographic ordering of the name variable. Without modification to the main method, the program should now output the students ordered by name.
Listing 8.2
public class Student extends Person
{
private int studentNumber;
public Student()
{
super();
studentNumber = 0;//Indicating no number yet
}
public Student(String initialName, int initialStudentNumber)
{
super(initialName);
studentNumber = initialNumber;
}
public void reset(String newName, int newStudentNumber)
{
setName(newName);
studentNumber = newStudentNumber;
}
public int getStudentNumber()
{
return studentNumber;
}
public void setStudentNumber(int newStudentNumber)
{
studentNumber = newStudentNumber;
}
public void writeOutput()
{
System.out.println("Name: " + getName());
System.out.println("Student Number: " + studentNumber);
}
public boolean equals(Student otherStudent)
{
return this.hasSameName(otherStudent) &&
(this.studentNumber == otherStudent.studentNumber);
}
}
Step by Step Answer:
Java An Introduction To Problem Solving And Programming
ISBN: 9780134462035
8th Edition
Authors: Walter Savitch