如果2名学生的教育水平相同,我可以根据平均分数比较2个学生对象。如果声明在外面返回什么?
public int compareTo(Student o) {
if(this.getLevel() == o.getLevel()) {
if(this.getAverage() > o.getAverage()) {
return 1;
} else if(this.getAverage() < o.getAverage()) {
return -1;
} else {
return 0;
}
}
}
答案 0 :(得分:1)
比较等级。如果是这样的话:
return Integer.compare(getLevel(), o.getLevel());
整个代码:
int comparison = Integer.compare(getLevel(), o.getLevel());
if (comparison == 0) {
comparison = Integer.compare(getAverage(), o.getAverage());
}
return comparison;
答案 1 :(得分:1)
首先,比较级别,如果结果为0
,则比较平均值:
public int compareTo(Student o) {
int result = Integer.compare(this.getLevel(), o.getLevel());
if (result == 0) {
result = Integer.compare(this.getAverage(), o.getAverage());
}
return result;
}
使用Java 8 +中的Comparator
接口
public int compareTo(Student o) {
return Comparator.comparingInt(Student::getLevel)
.thenComparingInt(Student::getAverage)
.compare(this, o);
}