
304
8
章
Comparable
を実装する
public class Duck implements Comparable<Duck> {
String name;
int weight;
public Duck(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String toString() {
return name + "
の重さは
" + weight;
}
public int compareTo(Object otherDuck) {
if (this.weight < otherDuck.weight) {
return -1;
} else if (this.weight == otherDuck.weight) {
return 0;
} else { //
つまり
this.weight > otherDuck.weight
の場合
return 1;
}
}
}
Duck
を比較する
Duck
をソートしたい場合には、この
compareTo()
メソッドを実装しなければいけません。このメソッ
ドを実装すれば、
Arrays
クラスでアルゴリズムを完成
させカモをソートすることができます。
以下はカモの実装です。
サブクラス化していないので、
Comparable
インタ
フェースを実装する必要があります。
この
Duck
は、名前と重さを持っています。
シンプルにしています。
Duck
は名前と重 ...