We need to sort the objects, but the objects are not specific numeric values like the basic types
If you want to compare objects, you need to implement either of the two interfaces. Comparable Comparable Interface Comparator Comparator Interface
String wrapper, etc., implement the Comparable interface, and override the CompareTo () method
Rewrite compareto analogy equals method rewrite, get the content of attributes for comparison
Natural ordering
- this.field > obj.field 返回 +
-this <obj.field returns-
- this.field == obj.field 返回0
Custom class sorting also implements the Comparable interface and overrides the CompareTo () method
Custom sort
Custom class has multiple attributes
When the attributes of the main judgment are the same and cannot be compared
Multiple attribute judgments can be superimposed, that is, the same int is more than double, and the same char is more than String,
- this.field == obj.field 再判断 this.field2 和 obj.field2
Comparator custom sort, comparator
Rewrite compare method to compare object size
Positive number o1> o2
Negative number o1 <o2
0 o1 == o2
Comparable & Comparator difference?
Comparable is suitable for setting a fixed sorting method
Comparator is used to temporarily customize sorting, the sorting method is more flexible