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

I know, it is fairly simple to many of you, yet I would like to clear the doubts. At first sight, it looks like the recursive function or it is like calling the parent compareTo function.

However, after the research, I tend to think those two compareTo methods are different. The first one that is actually being overridden is from the Comparable interface, and the second is from the String class. Thus, we can call compareTo from the String class while overriding the Comparable compareTo method.

Please, confirm my thoughts. Thank you.

max
  • 166
  • 13

2 Answers2

1
 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
Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47
1

Consider this.

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

In the above case, I only want MyClass instances to be comparable on a single field (I could have more if I choose). So the other call is simply taking advantage of the Object's (Integer in this case) own compareTo method. This also means that in this case, MyClass has the same natural ordering of Integer.

WJS
  • 36,363
  • 4
  • 24
  • 39