Comparators
- 2 types of comparators
- Comparable: for setting a DEFAULT sorting for all objects of a class
- Comparator: for creating a special case sorting schema for an object
- Comparable usage
- Implement comparable to the class that you want to make sortable
- Implement the compare method in the class.
- Make it compare a field value in the two classes.
- Return
n
for earlier obj, +n
for later obj
- Comparator usage
- Create a new class for your sorting schema. Implement the comparato
SortByName implements comparator<Obj>
- Inside class, implement the compare method. Same way as for
comparable
.
- Feed new
SortingSchema
obj into the Collections.sort()
method.