Say we have a class with an int and a string. I can determine how one object of this class can be compared with another.
I could choose any criteria. For example, I can decide to sort based on int. If I have two ints with the same value, I can select the line as an additional criterion, something like this:
class CustomObject implements Comparable<CustomObject> {
String aString;
int aInt;
...
public int compareTo(CustomObject two ) {
int diff = this.aInt - two.aInt;
if( diff != 0 ) {
return diff;
}
return this.aString.compareTo( two.aString );
}
...
}
Here is the full working demo ...
import java.util.*;
class SortDemo {
public static void main( String ... args ) {
List<CustomObject> list = Arrays.asList(
new CustomObject(3, "Blah"),
new CustomObject(30, "Bar"),
new CustomObject(1, "Zzz"),
new CustomObject(1, "Aaa")
);
System.out.println( "before: "+ list );
Collections.sort( list );
System.out.println( "after : "+ list );
}
}
class CustomObject implements Comparable<CustomObject> {
String aString;
int aInt;
CustomObject( int i, String s ) {
aInt = i;
aString = s;
}
public int compareTo(CustomObject two ) {
int diff = this.aInt - two.aInt;
if( diff != 0 ) {
return diff;
}
return this.aString.compareTo( two.aString );
}
public String toString(){
return "CustomObject[aInt="+aInt+", aString="+aString+"]";
}
}
Here's the conclusion:
before: [CustomObject[aInt=3, aString=Blah], CustomObject[aInt=30, aString=Bar], CustomObject[aInt=1, aString=Zzz], CustomObject[aInt=1, aString=Aaa]]
after : [CustomObject[aInt=1, aString=Aaa], CustomObject[aInt=1, aString=Zzz], CustomObject[aInt=3, aString=Blah], CustomObject[aInt=30, aString=Bar]]
Hope that is clear enough
You can also pass a custom comparator. Let me know if you need a sample of this.