私はComparable
を実装する非常に基本的なコードを、年、アーティスト、タイトルに基づいて比較しています。Comparable Missing One traitを実装しています
しかし、私のコードは、タイトル、年、アーティストだけで絵を比較していません。
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Painting p1 = new Painting(Year.NINETYEIGHT, artist.ART1, title.TIT1);
Painting p2 = new Painting(Year.NINETYEIGHT, artist.ART1, title.TIT2);
System.out.println("p1: " + p1.toString());
System.out.println("p2: " + p2.toString());
if(p1.compareTo(p2)> 0){
System.out.println(p1.toString() + " beats " + p2.toString());
} else if(p1.compareTo(p2) < 0){
System.out.println(p2.toString() + " beats " + p1.toString());
} else{
System.out.println("Same Everything");
}
}
}
public enum Year {
NINETYSEVEN, NINETYEIGHT, NINETYNINE, TWOTHOUSAND
}
public enum artist {
ART1, ART2, ART3,
}
public enum title {
TIT1, TIT2,TIT3,
}
public class Painting implements Comparable {
private title title;
private Year year;
private artist artist;
public Painting(Year y, artist a, title t) {
title = t;
year = y;
artist = a;
}
@Override
public int compareTo(Object o) {
//compare values
Painting other = (Painting) o;
int yearCompare = this.year.compareTo(other.year);
int artistCompare = this.artist.compareTo(other.artist);
if (yearCompare == 0) {
//same year, compare artist
return this.artist.compareTo(other.artist);
} else if (artistCompare == 0) {
return this.title.compareTo(other.title);
} else {
return yearCompare;
}
}
@Override
public String toString() {
return title.name() + " by " + artist.name() + " produced " + year.name();
}
}
[カスタムソートを行うためにコンパレータを使用する]の可能な複製(http://stackoverflow.com/questions/5245093/using-comparator-to-make-custom-sort) –