02 Comparableインタフェースを学習するjava.langソース

I.はじめに

  それらとコレクションとの間の関係が表示されていないが、Javaのコレクションフレームワークの中では、かなりの程度まで、さまざまな操作のコレクションは、同等と比較不可分であるが、彼らは唯一の内側の収集時にパワーを最大限に高めることができます。ここで我々の分析の始まりです。

II。ソース

/**
   This interface imposes a total ordering on the objects of each class that
   implements it.  This ordering is referred to as the class's <i>natural
   ordering</i>, and the class's <tt>compareTo</tt> method is referred to as
   its <i>natural comparison method</i>.

 此接口对实现它的每个类的对象强加一个总排序。这种排序被称为类的<i>自然排序</ i>,
 而类的<tt> compareTo </ tt>方法被称为其<i>自然比较方法</ i>。
 <p>

   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}).  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}.

 实现此接口的对象的列表(和数组)可以通过{@link Collections#sort(List)Collections.sort}
 (以及{@link Arrays#sort(Object [])Arrays.sort})自动排序。实现此接口的对象可以用作
 {@linkplain SortedMap有序映射}中的键,
 也可以用作{@linkplain SortedSet有序集}中的元素,而无需指定{@linkplain Comparator比较器}。
 <p>

   The natural ordering for a class <tt>C</tt> is said to be <i>consistent
   with equals</i> if and only if <tt>e1.compareTo(e2) == 0</tt> has
   the same boolean value as <tt>e1.equals(e2)</tt> for every
   <tt>e1</tt> and <tt>e2</tt> of class <tt>C</tt>.  Note that <tt>null</tt>
   is not an instance of any class, and <tt>e.compareTo(null)</tt> should
   throw a <tt>NullPointerException</tt> even though <tt>e.equals(null)</tt>
   returns <tt>false</tt>.

 当且仅当<tt> e1.compareTo(e2)== 0 </ tt>具有时,
 <tt> C </ tt>的自然顺序被称为<i>与等于</ i>一致与<tt> C </ tt>的每个
 <tt> e1 </ tt>和<tt> e2 </ tt>相同的布尔值<tt> e1.equals(e2)</ tt>。请注意,
 <tt> null </ tt>不是任何类的实例,并且<tt> e.compareTo(null)</ tt>应该抛出<tt>
 NullPointerException </ tt>,即使<tt> e。
 equals(null)</ tt>返回<tt> false </ tt>。
 <p>

   It is strongly recommended (though not required) that natural orderings be
   consistent with equals.  This is so because sorted sets (and sorted maps)
   without explicit comparators behave "strangely" when they are used with
   elements (or keys) whose natural ordering is inconsistent with equals.  In
   particular, such a sorted set (or sorted map) violates the general contract
   for set (or map), which is defined in terms of the <tt>equals</tt>
   method.

 强烈建议(尽管不要求)自然排序与equals一致。这是因为没有显式比较器的有序集(和有序映射)
 在与自然顺序与equals不一致的元素(或键)一起使用时表现得“奇怪”。特别是,
 这样的有序集(或有序映射)违反了集合(或映射)的一般契约,它是根据<tt>等于</ tt>方法定义的。
 <p>

   For example, if one adds two keys <tt>a</tt> and <tt>b</tt> such that
   {@code (!a.equals(b) && a.compareTo(b) == 0)} to a sorted
   set that does not use an explicit comparator, the second <tt>add</tt>
   operation returns false (and the size of the sorted set does not increase)
   because <tt>a</tt> and <tt>b</tt> are equivalent from the sorted set's
   perspective.

 例如,如果添加两个键<tt> a </ tt>和<tt> b </ tt>,
 那么{@code(!a.equals(b)&& a.compareTo(b)== 0)}对于不使用显式比较器的有序集,
 第二个<tt> add </ tt>操作返回false(并且有序集的大小不会增加),
 因为<tt> a </ tt>和<tt> b </ tt>从排序集的角度来看是等价的。
 <p>

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

 几乎所有实现<tt> Comparable </ tt>的Java核心类都具有与equals一致的自然排序。
 一个例外是<tt> java.math.BigDecimal </ tt>,
 其自然顺序等同于具有相同值和不同精度的<tt> BigDecimal </ tt>对象(例如4.0和4.00)。
 <p>

   For the mathematically inclined, the <i>relation</i> that defines
   the natural ordering on a given class C is:<pre>
         {(x, y) such that x.compareTo(y) &lt;= 0}.
   </pre> The <i>quotient</i> for this total order is: <pre>
         {(x, y) such that x.compareTo(y) == 0}.
   </pre>

 对于数学倾向,定义给定类C的自然排序的<i>关系</ i>是:
 <pre> {(x,y),使得x.compareTo(y)&lt; = 0}。 </ pre>此总订单的<i>商</ i>是:
 <pre> {(x,y),使得x.compareTo(y)== 0}。 </ PRE>

   It follows immediately from the contract for <tt>compareTo</tt> that the
   quotient is an <i>equivalence relation</i> on <tt>C</tt>, and that the
   natural ordering is a <i>total order</i> on <tt>C</tt>.  When we say that a
   class's natural ordering is <i>consistent with equals</i>, we mean that the
   quotient for the natural ordering is the equivalence relation defined by
   the class's {@link Object#equals(Object) equals(Object)} method:<pre>
       {(x, y) such that x.equals(y)}. </pre>

 它紧跟在<tt> compareTo </ tt>的合同之后,
 该商是<tt> C </ tt>上的<i>等价关系</ i>,
 并且自然排序是<i>总数在<tt> C </ tt>上订购</ i>。
 当我们说一个类的自然排序<i>与equals </ i>一致时,
 我们的意思是自然排序的商是由类{@link Object#equals(Object)equals(Object)定义的等价关系。
方法:<pre> {(x,y)使得x.equals(y)}。 </ PRE>
 <p>

   This interface is a member of the
   <a href="{@docRoot}/../technotes/guides/collections/index.html">
   Java Collections Framework</a>.

此界面是<a href="{@docRoot}/../technotes/guides/collections/index.html">
Java Collections Framework </a>的成员。

   @param <T> the type of objects that this object may be compared to

   @author  Josh Bloch
   @see java.util.Comparator
   @since 1.2
 */
public interface Comparable<T> {
    /**
       Compares this object with the specified object for order.  Returns a
       negative integer, zero, or a positive integer as this object is less
       than, equal to, or greater than the specified object.

     将此对象与指定的对象进行比较以获得顺序。返回负整数,零或正整数,因为此对象小于,等于或大于指定对象

       <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==
       -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>.  (This
       implies that <tt>x.compareTo(y)</tt> must throw an exception iff
       <tt>y.compareTo(x)</tt> throws an exception.)

     对于所有<tt> x </ tt>和<tt> y </ tt,实现者必须确保<tt> sgn(x.compareTo(y))== -sgn(y.compareTo(x))
     </ tt> >。
     (这意味着<tt> x.compareTo(y)</ tt>必须抛出异常iff <tt> y.compareTo(x)</ tt>抛出异常。)

       <p>The implementor must also ensure that the relation is transitive:
       <tt>(x.compareTo(y)&gt;0 &amp;&amp; y.compareTo(z)&gt;0)</tt> implies
       <tt>x.compareTo(z)&gt;0</tt>.

     实现者还必须确保关系是可传递的:<tt>(x.compareTo(y)&gt; 0&amp; y.compareTo(z)&gt; 0)
     </ tt>暗示<tt> x.compareTo( Z)大于0 </ tt>的。

       <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt>
       implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for
       all <tt>z</tt>.

     最后,实现者必须确保<tt> x.compareTo(y)== 0 </ tt>意味着<tt>
     sgn(x.compareTo(z))== sgn(y.compareTo(z))</ tt>,对于所有<tt> z </ tt>。

       <p>It is strongly recommended, but <i>not</i> strictly required that
       <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>.  Generally speaking, any
       class that implements the <tt>Comparable</tt> interface and violates
       this condition should clearly indicate this fact.  The recommended
       language is "Note: this class has a natural ordering that is
       inconsistent with equals."

     强烈建议,但<i>不</ i>严格要求<tt>(x.compareTo(y)== 0)==(x.equals(y))</ tt>。一般来说,任何实现<tt> Comparable </ tt>
     接口且违反此条件的类都应清楚地表明这一事实。推荐的语言是“注意:此类具有与equals不一致的自然顺序。”

       <p>In the foregoing description, the notation
       <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
       <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
       <tt>0</tt>, or <tt>1</tt> according to whether the value of
       <i>expression</i> is negative, zero or positive.

     在前面的描述中,符号<tt> sgn(</ tt> <i>表达式</ i> <tt>)</ tt>
     指定数学<i> signum </ i>函数,该函数被定义为返回<tt> -1 </ tt>,
     <tt> 0 </ tt>或<tt> 1 </ tt>中的一个,根据<i>表达式</ i>的值是否为负,零或正。

       @param   o the object to be compared.
       @return  a negative integer, zero, or a positive integer as this object
                is less than, equal to, or greater than the specified object.

       @throws NullPointerException if the specified object is null
       @throws ClassCastException if the specified object's type prevents it
               from being compared to this object.
     */
    public int compareTo(T o);
}

II。例

  正式に匹敵説明する前に、我々はそれらを使用するための直感的な感じに例があります。

public class Student implements Comparable<Student>{
    private Integer age;
    private Integer id;
    private String name;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != null ? !age.equals(student.age) : student.age != null) return false;
        return id != null ? id.equals(student.id) : student.id == null;
    }

    @Override
    public int hashCode() {
        int result = age != null ? age.hashCode() : 0;
        result = 31 * result + (id != null ? id.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public int compareTo(Student anthor) {
        if (this.age < anthor.age)
            return -1;
        else if (this.age == anthor.age)
            return this.name.compareTo(anthor.name);
        else
            return 1;
    }
}



    @Test
    public void test01(){
        List<String> list = new ArrayList<String>(){};
        list.add("11");
        list.add("13");
        list.add("12");
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
    }
    @Test
    public void test02(){
        List<Student> students = new ArrayList<Student>();
        Student student = new Student();
        student.setAge(1);
        Student student02 = new Student();
        student02.setAge(3);
        Student student03 = new Student();
        student03.setAge(2);

        students.add(student);
        students.add(student02);
        students.add(student03);
        System.out.println(students);
        Collections.sort(students);
        System.out.println(students);
    }

 

 綿密な研究や他の仕事の後、ライン上でほとんど十分

https://www.cnblogs.com/leesf456/p/5312136.html

 

おすすめ

転載: blog.csdn.net/weixin_38389755/article/details/93651266