My exercise says that i should implement a class called songs with a few methods. (see below) Afterwards i should code a method with given comparisons:
song1 < song2 if and only if
- song1.singer < song2.singer
- song1.singer = song2.singer ∧ song1.title < song2.title
- song1.singer = song2.singer ∧ song1.title = song2.title ∧ song1.year > song2.year
song1 = song2 if and only if
- song1.singer = song2.singer ∧ song1.title=song2.title ∧ song1.year = song2.year
song1 > song2 other
I implement the first comparison and it works but i have no idea how to write down the others. Do you have any hints?? I'm only allowed to use Comparable , not 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());
}
}
}
You can achieve your goal by this :