I think this code might be helpful
Sort java objects in an Array
Sorting in Java is Easy!
Author: email@example.com, Van Glass
There once was a time that sorting an array of primitives in Java took some work. And sorting an array of Objects involved even more. Nowadays we can sort arrays of primitives and Objects with relatively little code using the Comparable interface.
The java.util.Comparable interface is a class which when implemented will define the natural order for a pair of Objects. Currently there are only a handful of classes which by default implement the Comparable interface. One such class is the String class. In implementing the Comparable interface the String class overloads the compareTo(Object obj) method. The compareTo(Object obj) method returns a negative integer, zero, or a positive integer where the current instance is less than, equal to, or greater than object received.
The work has already been done for us in the String class. However if you want to provide sorting capabilities for your own classes then you must implement Comparable and overload the compareTo(Object obj) yourself. Here is a simple example which defines a class Student. Each Student has a studentid, first_name, last_name. According to our specifications Student should be sorted by student_id.
public class Student implements Comparable
public int student_id;
public String last_name;
public String first_name;
public Student(int student_id, String last_name, String first_name)
this.student_id = student_id;
this.last_name = last_name;
this.first_name = first_name;
/* Overload compareTo method */
public int compareTo(Object obj)
Student tmp = (Student)obj;
if(this.student_id < tmp.student_id)
/* instance lt received */
else if(this.student_id > tmp.student_id)
/* instance gt received */
/* instance == received */
Now that the Student class overloads the compareTo(Object obj) method we can easily sort an array of Student objects. This is done using the java.util.Array class and its static sort method. A main method has been added below to demonstrate how this would work.
public static void main(String args)
/* Create an array of Student object */
Student students = new Student;
students = new Student(52645,"Smith","Bob");
students = new Student(98765,"Jones","Will");
students = new Student(1354,"Johnson","Matt");
/* Sort array */
/* Print out sorted values */
for(int i = 0; i < students.length; i++)
students[i].last_name + students[i].first_name);
Simple right? With a little more work the Student class could be modified to sort on a combination of member variables. For instance you may want to sort first by last_name and then by student_id. Keep in mind that the Arrays class will sort any array including an array of primitives. With primitives however there is no need to implement Comparable making it very easy to sort int, float etc. Until next week.