我的练习说,我应该使用一些方法实现一个称为歌曲的类。 (见下文)
之后,我应该编写一个具有给定比较的方法:
song1
song1.singer song1.singer = song2.singer∧song1.title song1.singer = song2.singer∧song1.title = song2.title∧song1.year> song2.year
song1 = song2当且仅当
song1.singer = song2.singer∧song1.title = song2.title∧song1.year = song2.year
song1> song2其他
我实现了第一个比较,并且可以正常工作,但是我不知道如何写下其他比较。你有什么提示吗?
我只允许使用Comparable,而不是Comparator!
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Songs implements Comparable<Songs>{
private String singer;
private String title;
private Integer year;
Songs(String singer, String title, int year){
this.singer = singer;
this.title = title;
this.year = year;
}
public String getSinger(){
return this.singer;
}
public String getTitle(){
return this.title;
}
public int getYear(){
return this.year;
}
public String getCompleteName(){
return this.singer+"\t"+this.title.toString()+" - "+this.year.toString();
}
public int compareTo(Songs o) {
if (o.getSinger() == this.getSinger() ) {
return 0;
}
if (this.getSinger()==null) {
return 1;
}
if (o.getSinger() == null) {
return -1;
}
return this.getSinger().compareTo(o.getSinger());
}
public static void main(String[] args) {
List<Songs> list = new ArrayList<Songs>();
list.add(new Songs ("Birdman","Breathe", 1994));
list.add(new Songs ("Lgoony","Nebel", 2012));
list.add(new Songs ("Recondite","Cleric",2015));
list.add(new Songs ("Alpha", "Beta", 1023));
list.add(new Songs ("Cleric", "zoom", 1999));
list.add(new Songs ("Cleric", "boom", 1999));
Collections.sort(list);
for (Songs x : list) {
System.out.println(x.getCompleteName());
}
}
}
最佳答案
您可以通过以下方式实现目标:
@Override
public int compareTo(Songs o) {
int compare;
if ((compare = this.getSinger().compareTo(o.getSinger())) != 0) {
return compare;
} else if ((compare = this.getTitle().compareTo(o.getTitle())) != 0) {
return compare;
}
return this.getYear() - o.getYear();
}
关于java - 如何在compareTo()中做更多比较?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41187364/