J'utilise un Max-Heap pour stocker des objets de type Song
. Une chanson a un titre et une note comme indiqué dans la classe Song
. Je veux que l'on compare l'objet Song
selon la cote afin que les titres les mieux notés soient affichés en premier. Si les chansons ont la même note, elles doivent être comparées par ordre alphabétique des titres. Ce que j'ai maintenant est en train de le sortir par la plus haute note, mais incorrectement.Comparaison des valeurs d'un objet avec compareTo()
Heap:
public class Heap<T extends Comparable<T>> {
private ArrayList<T> heap;
public Heap(){
heap = new ArrayList<T>();
}
public int getPLoc(int i){
return (i - 1)/2;
}
public int getLCLoc(int i){
return 2 * i + 1;
}
public int getRCLoc(int i){
return 2 * i + 2;
}
public T getNodeAt(int i) {
if(heap.get(i) == null) {
System.out.println("Item does not exist.");
return null;
}else {
return heap.get(i);
}
}
public void addNode(T n) {
heap.add(null);
int index = heap.size() - 1;
while(index > 0 && (getNodeAt(getPLoc(index)).compareTo(n)) < 0) { //Is this correct?
heap.set(index, getNodeAt(getPLoc(index)));
index = getPLoc(index);
}
heap.set(index, n);
}
chanson:
public class Song implements Comparable<Song> {
private String title;
private String rating;
public Song(String t, String r) {
title = t;
rating = r;
}
public String getTitle(){
return title;
}
public String getRating(){
return rating;
}
// Need help here adding it to also compare by alphabetical title if songs have same ratings.
public int compareTo(Song s) {
return rating.compareTo(s.getRating());
}