JavaSE---Comparable

发布时间 2023-10-09 18:01:30作者: anpeiyong

概述

  This interface imposes a total ordering on the objects of each class that implements it.

    实现Comparable接口的每个class都可以排序;    

  This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

    实现Comparable接口的class是 自然排序,compareTo() 是 自然排序方法;    

  Lists (and arrays) of objects that implement this interface can be sorted automatically by {@link Collections#sort(List) Collections.sort} (and {@link Arrays#sort(Object[]) Arrays.sort}).  

    实现Comparable的对象 所属的list或数组,可以通过Collections#sort(List) Collections.sort} (and {@link Arrays#sort(Object[]) Arrays.sort} 进行排序;

  Objects that implement this interface can be used as keys in a {@linkplain SortedMap sorted map} or as elements in a {@linkplain SortedSet sorted set}, without the need to specify a {@linkplain Comparator comparator}.

    实现Comparable的对象 可以作为SortedMap、SortedSet的key(不需要指定Comparator);

  The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C.  

    class C 2个对象e1, e2 的自然排序 e1.compareTo(e2) == 0  等价于 e1.equals(e2);

   Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals.  One exception is java.math.BigDecimal, whose natural ordering equates BigDecimal objects with equal values and different precisions (such as 4.0 and 4.00).

    实际上,实现Comparable的Java核心类库 的自然排序 与 equals 一致;

    一个例外是BigDecimal, new BigDecimal(4.0) 与 new BigDecimal(4.00)  compareTo = 0 、equals = true;

  Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

    compareTo() 左<右 -> 负数、左=右 -> 0、左>右 -> 正数;