@Override 中的内部 compareTo() 方法引起的混乱

问题描述

        @Override
        public int compareto(StockItem o){
            if(o != null)
                return this.itemName.compareto(o.getItemName());
        }

我知道,这对你们中的许多人来说相当简单,但我想消除疑惑。乍一看,它看起来像递归函数或者调用父compareto函数

但是,经过研究,我倾向于认为这两种 compareto 方法是不同的。第一个实际上被覆盖的来自 Comparable 接口,第二个来自 String 类。因此,我们可以在覆盖 Comparable compareto 方法的同时从 String 类调用 compareto

请确认我的想法。谢谢。

解决方法

 public int compareTo(StockItem o){  <---- this refers to your Class  

 this.itemName.compareTo(o.getItemName());  <---- this calls compareTo() method of another Class that
    //you refer on your class. So you have maybe a ItemName itemName on your main class
    //as a field and maybe ItemName is String class I don't know.
    //but this compareTo is called on the Class of that field whatever that is
,

考虑一下。

class MyClass implements Comparable<MyClass> {
   private Integer value;
   // other fields and constructors here too
   @Override
   public int compareTo(MyClass m) {
        Objects.requireNonNull(m);
        return value.compareTo(m.value);
   }
}

在上述情况下,我只希望 MyClass 实例在单个字段上具有可比性(如果我选择,我可以拥有更多)。所以另一个调用只是利用对象(在本例中为整数)自己的 compareTo 方法。这也意味着在这种情况下,MyClass 具有与 Integer 相同的自然顺序。