我的练习说我应该用一些方法实现一个叫做歌曲的课程。 (见下文) 之后我应该用给定的比较编写一个方法:
song1<歌曲2当且仅当
song1 = song2当且仅当
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());
}
}
}
答案 0 :(得分:1)
您可以通过以下方式实现目标:
@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();
}
答案 1 :(得分:1)
我会这样做
@Override
public int compareTo(Songs song) {
int val=0 ;
if(!singer.equals(song.getSinger())){
return singer.compareTo(song.getSinger());
}
else if (!title.equals(song.getTitle())){
return title.compareTo(song.getTitle());}
else {return -1*song.getYear().compareTo(year);}
}