我有一个包含三个字段(所有字符串类型)的“报告”对象列表-
ReportKey
StudentNumber
School
我有一个排序代码,就像-
Collections.sort(reportList, new Comparator<Report>() {
@Override
public int compare(final Report record1, final Report record2) {
return (record1.getReportKey() + record1.getStudentNumber() + record1.getSchool())
.compareTo(record2.getReportKey() + record2.getStudentNumber() + record2.getSchool());
}
});
由于某种原因,我没有排序顺序。一个建议在字段之间插入空格,但是为什么呢?
您认为代码有什么问题吗?
最佳答案
是。为什么在比较它们之前将三个字段加在一起?
我可能会做这样的事情:(假设字段按照您希望对其进行排序的顺序)
@Override public int compare(final Report record1, final Report record2) {
int c;
c = record1.getReportKey().compareTo(record2.getReportKey());
if (c == 0)
c = record1.getStudentNumber().compareTo(record2.getStudentNumber());
if (c == 0)
c = record1.getSchool().compareTo(record2.getSchool());
return c;
}