Student class that has instance variables implement the interface
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.
Answer:
/** Exploring the Comparable interface with sorting.*/
import java.util.Arrays;
public class Question
{
public static void main(String[] args)
{
Student[] students = new Student[5];
students[0] = new Student("Kenrick",43);
students[1] = new Student("Khristy", 34);
students[2] = new Student("Kelton", 99);
students[3] = new Student("Kyler", 85);
students[4] = new Student("Karsten", 42);
Arrays.sort(students);
for (Student s : students)
{
System.out.println(s.toString());
}
}
}
public class Student implements Comparable
{
private String lastName;
private int ID;
public Student()
{
lastName = "";
ID = 0;
}
public Student(String theName, int theID)
{
lastName = theName;
ID = theID;
}
public String getLastName()
{
return lastName;
}
public int getID()
{
return ID;
}
public int compareTo(Object other)
{
Student otherStudent = (Student) other;
/*
* Uncomment this to compare by ID number instead of lastname
if (ID == otherStudent.ID) return 0;
if (ID < otherStudent.ID) return -1;
return 1;
*/
return lastName.compareTo(otherStudent.lastName);
}
public String toString()
{
return lastName + " " + ID;
}
}
Leave a reply