SORTING A CLASS OF RECORDS WITH Comparable

advertisement
SORTING A CLASS OF RECORDS WITH
THE Comparable INTERFACE
So far we have learned how to sort data using the static methods (i.e. sort()
and reverseOrder()) included in the Collections class. But what if we
wanted to sort multiple data? For example, what if we had a file that
contained names, student numbers and grade level and we wanted to sort
that data by student number. Simply storing the data in three separate
ArrayList or LinkedList objects won’t do it because as one of the lists gets
sorted the others need to be sorted in the same way. The following lesson
will address this issue by going through the steps required for sorting multiple
data.
IMPLEMENTING THE Comparable INTERFACE
The Comparable interface is part of the java.lang package, and it contains one method:
compareTo(). The compareTo() method returns the following values:



A negative number if the calling object “comes before” the object that is passed to it.
A zero if the calling object “equals” the object that is passed to it.
A positive number if the calling object “comes after” the object that is passed to it.
So, if we want the Student class that we created in the previous lesson to include a functionality that
sorts the data, we would need to first implement the Comparable interface by adding the statement
implements Comparable to our class declaration:
public class Student implements Comparable<Student>
The next step would be to add a compareTo() method declaration which takes a single parameter of
type Object. You must then cast the parameter to your own type (in this case, Student), and then return
an int value indicating which of the two object is larger. Again, a negative value indicates that the
current object is smaller, a positive integer indicates the current object is larger and a zero indicates that
there is no difference. The following method can be used to compare out students by student number:
public int compareTo(Student s) {
int comparison = studentNumber.compareTo
(s.getStudentNumber()));
return comparison;
}
public String toString() {
return String.format(“%-15s%-25s%5s”, studentNumber, name,
grade);
}
The Comparable Interface
Page 1 of 5
The Student class is now a sortable type, which means we can add Student to sorted collections such
as LinkedList and ArrayList. As we add Student objects to our LinkedList, the LinkedList will use
the compareTo() method to establish the correct order by student number.
The toString() method is necessary to indicate the format in which you want to return the Student
object to the LinkedList object.
THE StudentDemo APPLICATION
Now that we have created our Student class, it is time to create a Java application that uses the class.
The following program will read the student numbers, names, and grades from the following unsorted
comma-delimited text file called students.txt:
The data will be stored in a LinkedList of Student objects, sorted, and then outputted to the system
console.
Here’s the code:
import java.util.*;
import java.io.*;
public class StudentDemo {
public static void main(String[] args) {
// Declare and initialize LinkedList object
LinkedList<Student> students = new LinkedList<Student>();
try
{
// Declare and initialize BufferedReader object
BufferedReader in = new BufferedReader(new FileReader(new
File("students.txt")));
// Declare variables
String line;
String[] data;
line = in.readLine();
The Comparable Interface
Page 2 of 5
while (line != null)
{
// Read data from file
data = line.split(", ");
students.add(new Student(data[0], data[1],
Integer.parseInt(data[2])));
line = in.readLine();
}
in.close();
}
catch (IOException e)
{}
// Sort data by student number in LinkedList object
Collections.sort(students);
// Output students to console sorted by student number
for (int i = 0; i < students.size(); i++)
{
System.out.println(students.get(i));
}
}
}
The above program should produce the following output:
SORTING IN REVERSE ORDER
To sort the list in reverse (or descending) order by student number would simply require the use of the
reverseOrder() method included in the Collections class:
Collections.sort(students, Collections.reverseOrder());
The Comparable Interface
Page 3 of 5
This would produce the following output:
SORTING MORE THAN ONE TYPE OF DATA
Let’s say we wanted to sort the list by grade and then by name. In order to do this we would need to do
this our compareTo() method would need to look something like this:
public int compareTo(Student s) {
int comparison = new Integer(grade).compareTo
(s.getGrade()));
if (comparison == 0)
{
int otherComp = name.compareTo(s.getName());
return otherComp;
}
else
{
return comparison;
}
}
The first thing you’ll notice with the above code is that when comparing an int data type (as we have
done in the above example), you need to make it an Integer object. The reason for this is that the
compareTo() method compares two different objects (not primitive types). So the same would apply
for example, if I were comparing a double data type; I would need to make it a Double object in order
for the compareTo() method to do its job.
The second important thing to note is that in order to sort more than one type of data (in the above
example, we’re sorting by grade and then by name), you will need an if statement whereby in the case
where the grades are equal, it will compare the names, and sort people with the same grades by their
names.
The above program, therefore, will produce the following output:
The Comparable Interface
Page 4 of 5
The Comparable Interface
Page 5 of 5
Download