public interface comparator<t>
A comparison function that forces the overall ordering of an object collection. You can pass Comparator to the sort method, such as Collections.sort or arrays.sort, allowing for precise control over the sort order. You can also use Comparator to control the order of certain data structures, such as ordered set or ordered mappings, or to provide sorting for objects that do not have a natural order collection.
The 1,2,3,4,5 of an integer: The a,b,c,d of a letter;
Natural sorting is used by default for the original type or string string type, and can be sorted directly using the collection class.
But if our custom object is added to the collection class that needs to be sorted, the collection class does not know its collation and needs to tell the collection class the collation of the new object.
We need to implement our own sort class, i.e. implement comparator.
Implementing comparator requires implementing its Compare method:
int compare (object O1, Object O2) The method returns an integer of the base type, returns a negative number that represents O1 less than O2, returns 0 for O1 and O2 equal, and returns a positive number that represents O1 greater than O2.
Public class treesettest { public static void main (String [] args) { treeset tree = new treeset ( New mycomparator ()); tree.add (New Person); tree.add (New person); tree.add (New person); tree.add (new Person ()); System.out.println (tree); //[20, 21, 24, 33] }}class person{ int age; string name; public person (int age) { this.age = age; } &Nbsp; public string tostring () { return string.valueof (this.age); }}class mycomparator implements Comparator{ public int compare (OBJECT&NBSP;O1,&NBSP;OBJECT&NBSP;O2) { Person p1 = (person) o1; Person p2 = (person) o2; return p1.age - p2.age; }}
TreeSet's storage is ordered, and our custom person object's collation requires us to customize the Mycomparator and tell the TreeSet constructor so that TreeSet can store our custom person objects, And sort the stored objects according to the sort rules we define. (Sort by the Age property size of person).
Java Record -61-Comparator comparator