![](/img/trans.png)
[英]How to declare Java List of Object where each one implements Comparable
[英]Implements Comparable Missing One trait
因此,我正在研究一个非常基本的代码,该代码实现了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();
}
}
ang 减慢几秒钟。 哈哈。 我想出了与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>
这样,您将不使用“原始”对象类型,而使用Painting类的compareTo()方法签名将变为:
public int compareTo(Painting o)
换句话说,您不必强制转换或担心检查参数是否是Painting的实例!
您的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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.