@Override
public int compareTo(StockItem o){
if(o != null)
return this.itemName.compareTo(o.getItemName());
}
我知道,这对你们中的许多人来说相当简单,但我想澄清这些疑虑。乍一看,它看起来像递归函数,或者它就像调用父compareTo函数。
然而,经过研究,我倾向于认为这两种比较方法是不同的。实际被重写的第一个来自Comparable接口,第二个来自String类。因此,我们可以从String类调用compareTo,同时重写Comparable 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
实例在单个字段上具有可比性(如果我选择的话,我可以有更多(。因此,另一个调用只是利用Object(在本例中为Integer(自己的compareTo
方法。这也意味着在这种情况下,MyClass
具有与Integer
相同的自然排序。