gpt4 book ai didi

java - 使用compareTo()比较对象的值

转载 作者:行者123 更新时间:2023-11-30 03:11:36 25 4
gpt4 key购买 nike

我正在使用 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());
}

最佳答案

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

关于java - 使用compareTo()比较对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33513741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com