使用compareTo()比较Object的值

时间:2015-11-04 04:32:13

标签: java heap comparable compareto

我使用Max-Heap来存储Song类型的对象。歌曲的标题和评级如Song课程所示。我希望通过评级来比较Song对象,以便首先显示评分最高的歌曲。如果歌曲具有相同的评级,则应按字母顺序排列。我现在所拥有的是按最高评分输出,但不正确。

堆:

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);
}

曲:

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());
}

2 个答案:

答案 0 :(得分:2)

compareTo()方法返回int,其中包含以下值:

否定如果thisObject < anotherObject

如果thisObject == anotherObject

正面如果thisObject > anotherObject

Check for value zero,意思是评分相同,然后转到title comparison

示例代码,可以调整

public int compareTo(Song s) {
    int val = rating.compareTo(s.getRating());
      if(val == 0){
         val = title.compareTo(s.getTitle());
      }
    return val;
}

答案 1 :(得分:0)

解决方法是比较歌曲的名称,如果他们的Rank相等(并且compareTo因此返回0)并返回第二次比较的结果