一、Comparator方法
Comparator 是 Java 中的一个接口,用于定义对象的排序顺序。这个接口的核心方法是 compare,用于比较两个对象并决定它们的排序顺序。里面提供了ComparingDouble,comparingInt等直接比较方法,也提供了nullsLast,nullsFirst(如果对象为空,则优先于非空对象的排序)等方法,要定制Comparator方法,就要重写里面的Compare方法。
二、例子
重写Comparator就需要重写里面的compare方法
/**
* Compares its two arguments for order. Returns a negative integer,
* zero, or a positive integer as the first argument is less than, equal
* to, or greater than the second.<p>
*
* The implementor must ensure that {@code sgn(compare(x, y)) ==
* -sgn(compare(y, x))} for all {@code x} and {@code y}. (This
* implies that {@code compare(x, y)} must throw an exception if and only
* if {@code compare(y, x)} throws an exception.)<p>
*
* The implementor must also ensure that the relation is transitive:
* {@code ((compare(x, y)>0) && (compare(y, z)>0))} implies
* {@code compare(x, z)>0}.<p>
*
* Finally, the implementor must ensure that {@code compare(x, y)==0}
* implies that {@code sgn(compare(x, z))==sgn(compare(y, z))} for all
* {@code z}.<p>
*
* It is generally the case, but <i>not</i> strictly required that
* {@code (compare(x, y)==0) == (x.equals(y))}. Generally speaking,
* any comparator that violates this condition should clearly indicate
* this fact. The recommended language is "Note: this comparator
* imposes orderings that are inconsistent with equals."<p>
*
* In the foregoing description, the notation
* {@code sgn(}<i>expression</i>{@code )} designates the mathematical
* <i>signum</i> function, which is defined to return one of {@code -1},
* {@code 0}, or {@code 1} according to whether the value of
* <i>expression</i> is negative, zero, or positive, respectively.
*
* @param o1 the first object to be compared.
* @param o2 the second object to be compared.
* @return a negative integer, zero, or a positive integer as the
* first argument is less than, equal to, or greater than the
* second.
* @throws NullPointerException if an argument is null and this
* comparator does not permit null arguments
* @throws ClassCastException if the arguments' types prevent them from
* being compared by this comparator.
*/
int compare(T o1, T o2);
- 返回1,o1大于o2
- 返回0,o1等于o2
- 返回-1,o1小于o2
可以根据上面的规则,定义自己的自定义排序。