有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

compareto Java中可比较的接口比较什么?

我想知道Java中可比较的接口是什么。 假设我有两个节点,每个节点只有一个实例变量。为什么要点头呢。比较(节点2)是否有效

谢谢


共 (2) 个答案

  1. # 1 楼答案

    首先,阅读documentation

    This interface imposes a total ordering on the objects of each class that implements it. 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.

    {a2}方法:

    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.

    以下是一个示例:

    public class MyComparable implements Comparable< MyComparable >{
    
       private int value;
    
       @Override
       public int compareTo( MyComparable other ) {
          return this.value - other.value;
       }
    
       public MyComparable( int i ) {
          value = i;
       }
    
       public static void main( String[] args ) {
          MyComparable _12    = new MyComparable( 12 );
          MyComparable _42    = new MyComparable( 42 );
          MyComparable _12bis = new MyComparable( 12 );
          System.out.println( _12.compareTo( _42 ));
          System.out.println( _42.compareTo( _12 ));
          System.out.println( _12.compareTo( _12bis ));
       }
    }
    

    它输出:

    -30
    30
    0
    
    • -30(<;0)表示12<;42,毫不奇怪
    • 30(>;0)表示42>;12,好的
    • 0(=0)表示12等于12,似乎是正确的
  2. # 2 楼答案

    Comparable是一个接口,因此它不包含任何逻辑。具有implement Comparable的具体类必须实现.compareTo()方法,如here所述

    实现此接口意味着您希望该类能够将自身与另一个实例进行比较,并返回一个数值,表示该类应被视为比传入的实例“大”还是“小”。这通常用于集合中的排序

    例如:

    public class Node implements Comparable<Node> {
    
        private int id;
        private String name;
    
        public int compareTo(Node other) {
           return (this.id < other.id ) ? -1 : (this.id > other.id) ? 1 : 0;
        } 
    }