Note that you are overloading the compareTo
method in your above code, not overriding it.
The interface
you are implementing:
public interface Comparable<T> {
public int compareTo(T o);
}
Your implementation:
@Override
public int compareTo(Object t) {
//...
}
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 implements Comparator<T>
(See here).
Collections.sort()
and getting a sorted collection by adding into aTreeSet
? – Nombles