public int compareTo(Name other) {
int result = this.familyName.compareTo(other.familyName);
if (result == 0) {
result = this.firstName.compareTo(other.firstName);
}
return result;
}
我不能理解代码的肉,它如何用来比较名称。请解释这种比较方法
public int compareTo(Name other) {
int result = this.familyName.compareTo(other.familyName);
if (result == 0) {
result = this.firstName.compareTo(other.firstName);
}
return result;
}
我不能理解代码的肉,它如何用来比较名称。请解释这种比较方法
如果姓氏相同,则比较名字。
本质上是“按姓氏分组”。
这是实施Comparable
(见https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html)接口的类的compareTo
方法。如果对象相同,则将compareTo
的返回值定义为0
;如果参数按字典顺序排列,则返回值为< 0
;如果参数较少,则返回> 0
。
您在此处对象Name
的比较结果被授予familyName
属性的compareTo
方法。这意味着将当前Name
对象的familyName
属性与参数的familyName
属性进行比较。第二个compareTo
检查仅在Name
对象实例的familyName
属性相同时才执行。如果是这种情况,则比较firstName
。
它委托给字符串的'compareTo'方法。 – Carcigenicate
哪一部分不清楚? – shmosel
在业务逻辑的上下文中,委托给字符串类,如果姓氏相同,则按名字比较。 – varra