First, comparable interface
1, public interface comparable{
public int CompareTo (Object other);
}
2. When this object is less than, equal to, or greater than the other object, a value less than, equal to, or greater than 0 is returned accordingly.
3, if the object can not be compared, throw classcastexception
4, CompareTo () The order of definition is the natural order of the class, that is, this sort is most natural to the object of the class.
5, Equals () defines a natural equality relationship, two objects are equal, and returns ture.
6, many classes: String, Date, Java.io.Fil, and wrapper class all implement this interface.
Second, comparator interface
1, public interface comparator<t>{
public int Compare (T O1, To2);
Boolean equals (Object obj);
}
2, the class that does not implement the comparable interface, or the class that implements the comparable interface does not want to use CompareTo () to compare, you can use the comparator interface to compare (we need to implement this interface), and in
The order in which compare () is defined is called the comparer order.
3, for the overall sorting of the collection. Forces the overall ordering of elements of certain collection objects, such as TreeMap, TreeSet, SortedMap, and SortedSet, which can be assigned a comparer to these collection objects.
Third, where to need comparator
1. Classes that need to be compared, use comparable between the same class objects and are implemented by this class, not homogeneous or overall sort using comparator.
2. The set to be sorted
Java comparators: Comparable and comparator