There are two main ways of supporting object comparisons in Java.
You can have your class implement the Comparable
interface, which is acceptable when your objects have a natural ordering that you're relying on (for example, alphabetical ordering for strings). This requires classes to implement a compareTo
method which defines the comparison rule between instances.
The standard alternative is to instantiate a Comparator
for your class, and specify the comparison rule in a compare
method.
In your case, the latter option seems more appropriate. The mechanics of the compare
method are fairly simple: it takes two instances of your class, returns a negative value if the first is "less than" the second, a positive number if it is "greater", and 0 if they are "equal". For integer-based comparisons, like comparing by marks
, the quick trick is to return the difference of the numbers.
Once you have your Comparator
defined, sorting is as simple as invoking the Collections.sort
method, opting for the method signature which takes a List
and a specified Comparator
.
List<Emp> emps = new ArrayList<Emp>();
// populate list...
Comparator<Emp> empComparator = new Comparator<Emp>() {
public int compare(Emp e1, Emp e2) {
return e2.getMarks() - e2.getMarks();
}
};
Collections.sort(emps, empComparator);