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

Jai*_*odi 0 java object compareto comparable

我创建了一个Student类,其中包含卷号,名称和年龄作为其数据变量。我创建了一个ArrayList用于存储class的多个对象的Student

现在,我已使用该Comparable接口及其compareTo方法根据年龄对学生列表数据进行排序。

以下是compareTo我创建的按年龄排序的方法:

    public int compareTo(Student sNew)
    {
        return this.age-sNew.age;
    }
Run Code Online (Sandbox Code Playgroud)

在这里,我不明白,什么是-?以及它如何运作?

因为,我也这样做如下:

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;
    }
Run Code Online (Sandbox Code Playgroud)

因此,我有两个怀疑:compareTo()方法中的“-”如何工作以及它在哪里返回值(0,1,-1)。

请指导。

Nir*_*evy 7

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

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