@Override
public int compareTo(Object t)
{
if(t instanceof Student)
{
Student s = (Student)t;
return (this.name.compareTo(s.name));
}
else
return -1;
}
This is my compareTo
method implementation for comparing two Student
objects based on their name. Is it possible to compare two such objects based on multiple fields i.e., both name and age?
Apache CompareToBuilder class is worth a mention.
You can implement with or without reflection
Note that you are overloading the
compareTo
method in your above code, not overriding it.The
interface
you are implementing:Your implementation:
The original author of this interface, Josh Bloch, advised in his book Effective Java to use the
@Override
annotation just for this reason; bugs caused by overloading can be rather hard to spot.You say you want to compare these objects "based on multiple fields"- I'm not sure if this means "order them one way based on two fields" or "order them multiple ways, each based on a single field". Either are possible, as demonstrated in the other answers here.
However, this is the bottom line:
You should implement
Comparable<T>
if you are creating a class yourself, as you appear to be, and want to define a "natural ordering" for this class. If you want to define multiple orderings or you do not control the class in question, define your own ordering in a class that implementsComparator<T>
(See here).Yes it is possible to compare two objects based on different sort sequences using
Comparator
interfacecompare
method.You need to create a sort sequence class. Sorting user defined objects using comparator
Yes, but first you should type the Comparable interface you're implementing. Here's what it should look like:
Notice how with the typed interface
Comparable<Student>
, instead of the raw typeComparable
, there's no need to cast.