Create a Student class that has instance variables for the student’s last name and ID number, along with appropriate constructors, accessors, and mutators. Make the Student class implement the Comparable interface. Define the compareTo method to order Student objects based on the student ID number. In the 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 their last name. Without modification to the main method, the program should now output the students ordered by name.
PROGRAM CODE:
import java.util.Arrays;
public class Student implements Comparable<Student> {
private String lastName;
private int idNumber;
public Student(String lastName, int idNumber) {
this.lastName = lastName;
this.idNumber = idNumber;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
@Override
public int compareTo(Student other) {
// Compare based on student ID number
// return Integer.compare(idNumber, other.idNumber);
// Compare based on lexicographic ordering of last name
return lastName.compareTo(other.lastName);
}
@Override
public String toString() {
return "Student [lastName=" + lastName + ", idNumber=" + idNumber + "]";
}
public static void main(String[] args) {
Student[] students = new Student[5];
students[0] = new Student("Smith", 123);
students[1] = new Student("Johnson", 456);
students[2] = new Student("Williams", 789);
students[3] = new Student("Brown", 234);
students[4] = new Student("Davis", 567);
// Sort the students based on student ID number
// Arrays.sort(students);
// Sort the students based on last name
Arrays.sort(students);
// Output the sorted students
for (Student student : students) {
System.out.println(student);
}
}
}
OUTPUT OF THE PROGRM CODE:
Student[lastName=Brown, idNumber=234]
Student[lastName=Davis, idNumber=567]
Student [lastName=Johnson, idNumber=456]
Student[lastName=Smith, idNumber=123]
Student[lastName=Williams, idNumber=789]