Java(Student ID)のCompareTo()メソッド
質問
Javaの学習と比較方法に問題がある。私はグーグルを試してみましたが、私が必要なものにとってあまり助けはありませんでした。私は必要なのは
// 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;} //satisfies your null student requirement
return this.studentId > other.studentId ? 1 :
this.studentId < other.studentId ? -1 : 0;
}
.
compareTo()
は、other
オブジェクトが比較的小さい場合は正の値を返すと予想されます。あなたが三国軍事業者に精通していると仮定すると、それがこれがしていることがあることがわかります。そうでない場合は、if / elseと同等のものは次のようになります。
public int compareTo(StudentIF other) {
if (other == null) { return 1; } //satisfies your null student requirement
if (this.studentId > other.studentId) return 1;
else if (this.studentId < other.studentId) return -1;
else return 0; //if it's neither smaller nor larger, it must be equal
}
. 他のヒント
compareTo
インタフェースとして必要:
このオブジェクトの負の整数、ゼロ、または正の整数は、指定されたオブジェクトよりも小さい、またはそれ以上の整数です。
プラスNULL比較の追加要件は、他のパラメータがNULLかどうかを確認してから、比較するための減算を行うだけです。
public int compareTo(StudentIF other) {
if (other == null) {
return 1;
}
return this.id - other.id;
}
. 所属していません StackOverflow