» Sorting Objects by technobard |
|
(Login to remove green text ads)
Classes in Java make it possible to define complex data structures. No surprise there. However, the rules for sorting these structures is not predefined. Which attribute or method do you use to compare one object to another? Is this sort ascending or descending? The implementation of the Comparable interface answers these questions while being extremely easy to use.
Let’s start with the fundamentals.
==================================
Comparable is an interface which means that any class that wants to inherit its behavior must “implement” it as in:
Code:
class StrangeStuff implements Comparable {
int strange_id;
String moniker;
boolean et;
String principle_diet;
public int strangeFactor() {
int factor = 0;
if (et) {
factor = factor + 5;
}
factor = factor + principle_diet.length();
return factor;
}
…
Given object A and object B, any method comparing the two for sorting, needs to know:
a)Is A equal to B?
b)Is A greater than B?
c)Is A less than B?
Comparable answers these questions in the compareTo method; the details of which are specific to each class that implements it. For example:
Code:
public int compareTo (Object obj) {
StrangeStuff d = (StrangeStuff)obj;
if (strangeFactor() < d.strangeFactor()) {
return -1;
} else if (strangeFactor() > d.strangeFactor()) {
return 1;
}
return 0;
}
} // end of class definition: StrangeStuff
In the preceding code, compareTo compares the output of a method called strangeFactor() for the existing object and an object passed in (“obj”). It returns –1 for “less than”, returns 1 for “greater than”, and returns 0 when the two objects are equal.
The beauty of the Comparable interface is that any collection of objects that implements it can be sorted using the standard sort method. For Collections (i.e. Vector, LinkedList, etc.), you can use Collections.sort(listname). For Arrays, you can use Array.sort(arrayname).
Ascending vs Descending
=======================
One of the original questions was whether to sort in ascending or descending order. The default for a class is determined by the compareTo method definition. If you swap the return values for the “less than” and “greaer than” conditions, you will switch to an ascending sort. (The example shows a descending sort.)
Is There More?
==============
Sure. An alternative method of sorting is to use a Comparator. It is a less desirable solution (in my opinion) and so I leave it to the reader to investigate further.
Happy sorting!
|
|