我目前正在尝试按姓氏排序我的对象,首先是名字,然后是出生日期,然后是ssn。但从逻辑上讲,我只能想出姓氏,然后是名字,这有什么提示吗?
public int compareTo(Doctor o)
{
int result = this.lastName.compareTo(o.lastName());
return result == 0 ?this.firstName.compareTo(((Doctor) o).firstName()):result;
}发布于 2013-03-24 21:35:32
首先对姓氏进行排序。如果排序值为0,则按firstname排序。如果结果为0,则对出生日期进行排序,依此类推。当然,您会有多个return语句,但它的可读性要好得多。
正如您可能知道的,结果值为0表示这两个值相等。在您的用例中,这应该导致额外的排序,而不是简单地返回值。
编辑:下面的其他答案已经为此提供了确切的实现。
发布于 2013-03-24 21:37:41
嵌套的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;
}发布于 2013-03-24 21:38:04
您可以使用以下内容:
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());
}https://stackoverflow.com/questions/15599048
复制相似问题