gpt4 book ai didi

java - 实现类似的缺失一项特征

转载 作者:行者123 更新时间:2023-12-01 10:00:01 25 4
gpt4 key购买 nike

所以我正在编写一个非常基本的代码,它实现了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();
}

}

最佳答案

当当。慢了几秒钟。哈哈。我想出了与 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>

这样,您的 Paint 类的compareTo() 方法签名将变为:

public int compareTo(Painting o)

换句话说,您不必进行强制转换或担心检查参数是否是 Painting 的实例!

关于java - 实现类似的缺失一项特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36880630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com