了解Java中compareTo()方法的语法

问题描述 投票:0回答:2

我创建了一个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)。

请指导。

java object comparable compareto
2个回答
4
投票

其背后的想法是compareTo不返回0,1,-1,而是返回0(等于),正数(大于)或负数(较小)。

因此,只需减去年龄即可为您提供正确的答案


1
投票

[使用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);
}
© www.soinside.com 2019 - 2024. All rights reserved.