Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的compareTo()方法(学生ID)_Java_Compareto - Fatal编程技术网

java中的compareTo()方法(学生ID)

java中的compareTo()方法(学生ID),java,compareto,Java,Compareto,学习java和使用compareTo方法有困难。我试过谷歌,但对我所需要的帮助不大。我需要的是 // compareTo public int compareTo(Student other) // is defined in the Comparable Interface // and should compare the student ID's (they are positive integers). // Must be able to handle null "othe

学习java和使用compareTo方法有困难。我试过谷歌,但对我所需要的帮助不大。我需要的是

// compareTo public int compareTo(Student other) 
// is defined in the Comparable Interface
    // and should compare the student ID's  (they are positive integers).
// Must be able to handle null "other" students. A null student should be
// ordered before any student s so the s.compareTo(null) should be positive.
因此,基本上是一个比较,最终这个方法将帮助我根据最低到最高的学生ID对我的学生进行排序。。我现在处境艰难,只需要在正确的方向上得到一些帮助

public int compareTo(StudentIF other) {
    // do stuff
    return 0;
}
由于compareTo接口需要:

负整数、零或正整数,因为此对象小于、等于或大于指定对象

加上您对空比较的额外要求,我们可以简单地检查另一个参数是否为空,然后进行减法比较

public int compareTo(StudentIF other) {
    if (other == null) {
        return 1;
    }
    return this.id - other.id;
}
由于compareTo接口需要:

负整数、零或正整数,因为此对象小于、等于或大于指定对象

加上您对空比较的额外要求,我们可以简单地检查另一个参数是否为空,然后进行减法比较

public int compareTo(StudentIF other) {
    if (other == null) {
        return 1;
    }
    return this.id - other.id;
}

关于实现compareTo有一个很好的教程。也就是说,在学习如何做一些事情时,了解如何在我的特定用例中实现它通常对我很有帮助——因此,在这种情况下,我可以想象这样的事情就足够了:

public int compareTo(StudentIF other) {
    if (other == null) {return 1;} //satisfies your null student requirement
    return this.studentId > other.studentId ? 1 : 
                            this.studentId < other.studentId ? -1 : 0;
}

关于实现compareTo有一个很好的教程。也就是说,在学习如何做一些事情时,了解如何在我的特定用例中实现它通常对我很有帮助——因此,在这种情况下,我可以想象这样的事情就足够了:

public int compareTo(StudentIF other) {
    if (other == null) {return 1;} //satisfies your null student requirement
    return this.studentId > other.studentId ? 1 : 
                            this.studentId < other.studentId ? -1 : 0;
}

张贴你的学生班级张贴你的学生班级非常好的解释,这一切都是有道理的,但什么是让我是我的无效案例。我不知道会发生什么。很好的解释,这一切都是有道理的,但让我感到困惑的是我的无效案例。我不知道会发生什么。请加上一些评论。不鼓励只使用代码的答案。@aliteralmind我认为这个代码足够简单。。。不管怎样,我已经添加了插图。这是一个改进了很多的答案+1请添加一些评论。不鼓励只使用代码的答案。@aliteralmind我认为这个代码足够简单。。。不管怎样,我已经添加了插图。这是一个改进了很多的答案+1.