所以我正在研究一个非常基本的代码,它实现Comparable
比较基于年份,艺术家和标题的绘画。
然而,我的代码并没有按照标题来比较画作,只有年份和艺术家。
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();
}
}
答案 0 :(得分:1)
荡。慢了几秒钟。哈哈。我提出了与shmosel相同的解决方案。
public int compareTo(Painting other) {
int yearCompare = year.compareTo(other.year);
if (yearCompare != 0)
return yearCompare;
int artistCompare = artist.compareTo(other.artist);
if (artistCompare != 0)
return artistCompare;
return title.compareTo(other.title);
}
一个区别。我会考虑改变你的班级标题。具体来说,我会改变:
public class Painting implements Comparable
为:
public class Painting implements Comparable<Painting>
这样,而不是使用&#34; raw&#34;对象类型,你的绘画类的compareTo()方法签名将成为:
public int compareTo(Painting o)
换句话说,你不必抛弃或担心检查参数是否是绘画的实例!
答案 1 :(得分:0)
你的if-else逻辑在几个方面存在缺陷。它应该更像这样:
int yearCompare = this.year.compareTo(other.year);
if (yearCompare != 0) {
return yearCompare;
}
int artistCompare = this.artist.compareTo(other.artist);
if (artistCompare != 0) {
return artistCompare;
}
return this.title.compareTo(other.title);
另一方面,你应该使用泛型并避免投射:
public class Painting implements Comparable<Painting> {
@Override
public int compareTo(Painting other) {
// no casting necessary
}
}