我创建了一个Student
类,其中包含卷号,名称和年龄作为其数据变量。我创建了一个ArrayList
用于存储类Student
的多个对象。
现在,我已经使用Comparable
界面及其compareTo
方法根据年龄对学生列表数据进行排序。
下面是我为区分年龄而创建的compareTo
方法:
public int compareTo(Student sNew)
{
return this.age-sNew.age;
}
在这里,我不明白,什么是-
?以及它如何运作?
因为我也按照以下步骤进行了:
public int compareTo(Student sNew)
{
int returnValue=0;
if(this.age>sNew.age)
{
returnValue=1;
}else if(this.age<sNew.age){
returnValue=-1;
}else if(this.age==sNew.age)
{
returnValue=0;
}
return returnValue;
}
所以,我有两个疑问:compareTo()方法中的'-'如何工作以及它在哪里返回值(0,1,-1)。
请指导。
其背后的想法是compareTo
不返回0,1,-1,而是返回0(等于),正数(大于)或负数(较小)。
因此,只需减去年龄即可为您提供正确的答案
[使用comparedTo
时,0表示两个对象相同。大于0表示对象a大于对象b,小于0表示对象a小于对象b。
[如果需要,也可以尝试此]
public int comparedTo(Student sNew) {
Integer age1 = new Integer(this.age);
Integer age2 = new Integer(sNew.getAge());
return age1.comparedTo(age2);
}