我目前正在尝试先按姓氏对我的对象进行排序,然后是名字,然后是出生日期,然后是 ssn。但从逻辑上我只能想出是姓氏然后是名字的任何提示吗?
public int compareTo(Doctor o)
{
int result = this.lastName.compareTo(o.lastName());
return result == 0 ?this.firstName.compareTo(((Doctor) o).firstName()):result;
}
我目前正在尝试先按姓氏对我的对象进行排序,然后是名字,然后是出生日期,然后是 ssn。但从逻辑上我只能想出是姓氏然后是名字的任何提示吗?
public int compareTo(Doctor o)
{
int result = this.lastName.compareTo(o.lastName());
return result == 0 ?this.firstName.compareTo(((Doctor) o).firstName()):result;
}
首先按姓氏排序。如果排序值为0
,则按名字排序。如果结果是0
,则按出生日期排序,依此类推。当然,你会有多个return
语句,但它更具可读性。
您可能知道,结果值0
表示这两个值相等。在您的用例中,这应该导致额外的排序,而不是简单地返回值。
编辑:下面的其他答案为此提供了确切的实现。
嵌套 if 将是实现这一点的更好选择。
public int compareTo(Doctor o){
int result = this.lastName.compareTo(o.lastName());
if(result==0){
result = this.firstName.compareTo(o.firstName());
if(result==0){
result = this.dob.compareTo(o.dob());
if(result==0){
....
}
}
}
return result;
}
您可以使用以下内容:
public int compareTo(Doctor o)
{
int result = this.lastName.compareTo(o.lastName());
if (result != 0)
return result;
result = this.firstName.compareTo(o.firstName());
if (result != 0)
return result;
result = this.birthDate.compareTo(o.birthDate());
if (result != 0)
return result;
return this.ssn.compareTo(o.ssn());
}
您可能已经意识到,这是一种“责任链”。所以我会建议你这个案例的模式。责任链模式
它将使您免于编写太多 if()...s