You should use a Comparator or implement Comparable in your custom object.
Implementing a Comparable you define a natural ordering for your objects. In the Comparable.compareTo() method you have to compare the current object with another one and return
- a negative integer if the current object is "less than" the other one;
- zero if the current object is "equal" to the other one;
- a positive integer if the current object is "greater than" the other one.
An example:
public class CustomObject implements Comparable<CustomObject> {
@Override
public int compareTo(CustomObject otherOne) {
// Compare the current object with the otherOne and return an
// appropriate integer
return 0;
}
}
// To sort
Collections.sort(listOfCustomObjects);
From the other side, implementing a Comparator you can specify an ordering criteria outside the code of the custom Object. Using the appropriate Collections.sort() method, you can specify the order for the objects in a collection. The Comparator.compare() method follows the same rules explained above.
An example:
public class CustomObjectComparator implements Comparator<CustomObject> {
@Override
public int compare(CustomObject a, CustomObject b) {
// Compare a with b and return an appropriate integer
return 0;
}
}
// To sort
Collections.sort(list, new CustomObjectComparator());